Skip to content Skip to sidebar Skip to footer

Python Code To Swap First And Last Letters In String

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 i

Solution 1:

You probably got an IndexError for an empty string ('') as str[0] would be out of range in that case. As written, your code would also produce an invalid result for a 1-character string. To fix it, you can return the original string if its length is < 2. Also, it would be much simpler (and faster) to use string slicing:

def front_back(string):
    if len(string) < 2:
        return string
    return string[-1] + string[1:-1] + string[0]

(As a side note, don't use str for a variable name as it'll shadow the built-in str function).


Solution 2:

Your problem is with 1 character, ie. front_back('a') → 'a'. Consider how you could adjust your function to account for this case.

EDIT: I did not like the efficiency or generality of the other answers, so I'll post my solution below:

def front_back(str):
    return ''.join([x if i not in [0,len(str)-1] else str[len(str)-i-1] for i,x in enumerate(str) ])

Solution 3:

Keep it simple to avoid the special cases:

def front_back(string):
    array = list(string)
    array[0], array[-1] = array[-1], array[0]
    return "".join(array)

Solution 4:

I assume that the website uses a series of random/pseudorandom characters to determine if your code gives the correct output. If so then a string of len() == 1 would return incorrectly. i.e. 'h' return 'hh'. I have modified the code to correct this. Assuming that the website also asked you to return the data rather that print I also accounted for that. Good luck!

def front_back(str):
    if len(str) > 1:
        str = list(str)
        first = [str[0]]
        last = [str[-1]]
        middle = str[1:-1]
        return ''.join (last + middle + first)
    else:
        return str

print front_back('h')

Post a Comment for "Python Code To Swap First And Last Letters In String"