【发布时间】:2019-12-14 11:36:11
【问题描述】:
我正在尝试交换字符串的第一个和最后一个字符,但出现“字符串索引超出范围”错误。请帮忙
def front_back(str):
ind=len(str)-1
newstring=str.replace(str[0],str[ind])
newerstring=newstring.replace(newstring[ind],str[0])
return newerstring
【问题讨论】:
-
运行您的代码不会显示任何索引超出范围错误。也替换将替换char的所有实例,而不仅仅是第一个,最后你正在覆盖python内置类型的字符串,尝试给你的变量名称不是asme作为python内置名称
-
你检查字符串是否为空?
-
我使用了 python 2.7——为了澄清——不,字符串不是空的 Anand。它在函数内部,因此需要用户作为参数放入。
-
@AritraChakrabary 你显然没有阅读过
str.replace的文档,假设你有testing这个词,你的代码str.replace(str[0],str[ind])将首先插入参数,因此它变成str.replace('t', 'g')。替换的文档说Return a copy with ALL occurrences of substring old replaced by new.,所以你有t的任何地方都将被替换为g。所以testing变为gesging,因为所有t都被g替换。 -
@chris 你是对的。但是你能帮我解决这个问题吗?该程序确实正在替换 char 的所有实例。帮助。刚刚运行程序。