
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to Form a New String where the First Character and the Last Character have been Exchanged
When it is required to form a new string where the first and last characters are exchanged, a method can be defined that uses indexing to form the new string.
Below is the demonstration of the same −
Example
def exchange_val(my_string): return my_string[-1:] + my_string[1:-1] + my_string[:1] my_string = “Hi there how are you” print(“The string is :”) print(my_string) print(“The modified string is :”) print(exchange_val(my_string))
Output
The string is : Hi there how are you The modified string is : ui there how are yoH
Explanation
A method named ‘exchange_val’ is defined that takes a string as a parameter.
It uses indexing to exchange the first and last characters of a string.
Outside the method, a string is defined, and is displayed on the console.
This method is called by passing the string as a parameter to it.
This is displayed as output on the console.
- Related Articles
- How to remove the first and last character in a string in R?
- Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String
- Swift Program to remove the last specified character from the string
- First Unique Character in a String in Python
- Python Program to Get a Character From the Given String
- Program to find the index of first Recurring Character in the given string in Python
- Java Program to Capitalize the first character of each word in a String
- How to remove the last character from a string in Java?
- Remove the last character from a string in the Swift language
- Java Program to replace all occurrences of a given character with new character
- Golang program to capitalize first character of each word in a string
- How to find the first character of a string in C#?
- Python Program to Replace the Spaces of a String with a Specific Character
- Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character
- Python program to find Most Frequent Character in a String

Advertisements