Jammie Dodger Jammie Dodger - 5 months ago 7
Python Question

Why doesn't my front_back programme in Python work?

The task is:


Given a string, return a new string where the first and last chars have been exchanged.


def front_back(str):

if len(str)<=0:
return str

else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2

front_back("code")

Answer

Why?

It won't work because .replace() will replace all occurrences of that character, not necessarily only the first and last

Below is a solution that constructs the string with first, body and last portions

text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
Comments