features-Python-courses-python-exercises-python-oop

Exercise 76

Write a python algorithm that transform a given string s by swapping the second character (s[1]) with the befor last character. We assume that len(s) is greater or equal than 4. Example if s = "Python" , the algorithm returns the string: "Pothyn".

Solution

def swapping(s):
n = len(s)
s_swap = s[0] + s[n-2] + s[2:n-2] + s[1] + s[n-1]
return s_swap

# Example
s = "Python"
print(swapping(s)) # the output is : Pothyn

Younes Derfoufi
my-courses.net

Leave a Reply