Exercise20
Write a Python program, to swap the first and the last character of a given string.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 |
# define an example of string s s = "Python" # get the length of the string s n = len(s) # get the first character of the string s first = s[0] last = s[n-1] # extract the substring obtained from s ignoring the first and the last character s1 = s[1:n-1] # construct a new string by changing the first and last character s2 = last + s1 + first print(s2) # output: 'nythoP' |
Younes Derfoufi
CRMEF OUJDA
2 thoughts on “Solution Exercise 20: swapping the first character and the last character of a string in python”