【问题标题】:'string index out of range' when replacing first and last characaters of string?替换字符串的第一个和最后一个字符时“字符串索引超出范围”?
【发布时间】: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 的所有实例。帮助。刚刚运行程序。

标签: python string indexing


【解决方案1】:

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

【讨论】:

  • 谢谢,好节目!但问题是——为什么我不能用字符串对象上的替换方法来做到这一点
  • 但有一个问题。这个程序在 python 2.7 中不起作用---'字符串索引超出范围'!!!!!!!!!让我发疯。虽然这适用于 python 3
  • @AritraChakrabary 它也在 python2x 中工作(只是 print 不被称为函数)。您不能使用替换来修改同一个对象,因为它是非可变的。此功能有其自身的优点。
猜你喜欢
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2010-10-31
  • 1970-01-01
  • 2014-02-12
相关资源
最近更新 更多