Python program to swap characters of a given string; Through this tutorial, i am going to show you how to swap characters of a given string in python. As well as how to swap first and last character of given string in python.
Python program to swap characters of a given string
- 1: Python swap first and last character of string
- 2: Python swap characters of the string
1: Python swap first and last character of string
Use the following steps to swap first and last character of string in python:
- Define a function, which is used to swap characters of given string.
- Allow user to input a string.
- Call swap() with [ass the string as an argument to a function.
- Print result.
# swap characters in string def swap(str): if len(str) <= 1: return str mid = str[1:len(str) - 1] return str[len(str) - 1] + mid + str[0] # take string from user str1 = input("Please Enter String : ") print (swap(str1))
After executing the program, the output will be:
Please Enter String : hello oellh
2: Python swap characters of the string
Use the following steps to swap character of string in python:
- Define function, which is used to swap a string characters.
- Allow user to input a string and store it in a variable.
- Call function with Pass the string as an argument to a function.
- Print the result
# swap characters in string def swap(string): return string[-1:] + string[1:-1] + string[:1] # take string from user str1 = input("Please Enter String : ") print (swap(str1))
After executing the program, the output will be:
Please Enter String : dev ved
Recommended Python Tutorials
Recommended:-Python Program to ASCII Value of Character
Recommended:-Python Program to Calculate Compound Interest
Recommended:-Python Program to Check Leap Year
Recommended:-Python Program To Print Number Pattern
Recommended:-Python Program to Print Star Pattern
Recommended:-Python Program Calculate Sum of n Numbers
Recommended:-Python Program to Reverse Numbers
Recommended:-Python Program to Find Largest of n Numbers
Recommended:-Python Program to Find Power of Number
Recommended:-Python Program to Print Prime Number From 1 to N
Recommended:-Python Program to Find Square Root of Number
Recommended:-Python Program to Find Cube of Number
Recommended:-Python Palindrome Program
Recommended:-Python Program to Count Set Bits in a Number
Recommended:-Python Program for BMI Calculation
Recommended:-Python Program to Find Out Absolute Value
Recommended:-Python Random Number Generator Code
Recommended:-Python program for Zip, Zap and Zoom game
Recommended:-Python Program to Swap Two Numbers
Recommended:-Python Program to Find n-th term of Fibonacci Series
Recommended:-Python Program For Calculator