Given a string, return a new string where the first and last chars have been exchanged.
front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'
The above is one of the problems provided on www.codingBat.com I was attempting to solve and below is the code I wrote to do so.
def front_back(str):
str = list(str)
first = [str[0]]
last = [str[-1]]
middle = str[1:-1]
print ''.join (last + middle + first)
Now this code seems to work properly when I run it in python 2.7 on my computer but when running it on code bat I get the following error: "Error:list index out of range"
Now I think I have a pretty good idea of what this error means, but I don't understand why I am getting it due to the fact any indexes I am referencing are basically guaranteed to be in string of at least 2 characters.
str[1:-1]will go out of range for'a'since only index[0]and[-1]are valid - Cory Kramer