简体   繁体   English

替换字符串的第一个和最后一个字符时“字符串索引超出范围”?

[英]'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. String 对象是不可变的,这意味着它的元素不接受任何更改。 The .replace() method is just returning a new instance of string. .replace()方法只是返回一个新的字符串实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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