Python code to swap first and last letters in string

给你一囗甜甜゛ 提交于 2019-12-11 17:06:24

问题


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.


回答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).




回答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) ])



回答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)



回答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')


来源:https://stackoverflow.com/questions/37838032/python-code-to-swap-first-and-last-letters-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!