简体   繁体   中英

'string index out of range' when replacing first and last characaters of string?

I am trying to exchange the first and last characters of a string but 'string index out of range' error is occurring. Please help

def front_back(str):
        ind=len(str)-1
        newstring=str.replace(str[0],str[ind])
        newerstring=newstring.replace(newstring[ind],str[0])
        return newerstring

String objects are immutable, means it accepts no change in its elements. The .replace() method is just returning a new instance of string.

You can try this way:

def front_back(s):
    return s[-1] + s[1:-1] + s[0] if len(s) >= 2 else s

print(front_back('hi there'))  #output:  ei therh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM