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
![[App intégrée] 2025 Upgraded Vidéoprojecteur 1920 * 1080P FHD 4K Mini Projecteur Portable Dual Contrôle avec Souris Android TV WiFi 6 BT5.2 180° Rotation Compatible avec HDMI/TV Stick/USB](https://www.tresfacile.net/wp-content/uploads/2025/12/Videoprojecteur-1920-1080P-FHD-4K-Mini-Projecteur-Portable-Dual-Control-250x236.png)


2 thoughts on “Solution Exercise 20: swapping the first character and the last character of a string in python”