Jammie Dodger Jammie Dodger - 1 year ago 38
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

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


Answer Source


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'