![](/img/trans.png)
[英]IndexError string index out of range when referencing first character
[英]'string index out of range' when replacing first and last characaters of string?
我正在尝试交换字符串的第一个和最后一个字符,但出现“字符串索引超出范围”错误。 请帮忙
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 对象是不可变的,这意味着它的元素不接受任何更改。 .replace()方法只是返回一个新的字符串实例。
你可以试试这个方法:
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.