从某个索引替换一个字符

新手上路,请多包涵

如何从某个索引替换字符串中的字符?例如,我想从一个字符串中获取中间字符,比如 abc,如果这个字符不等于用户指定的字符,那么我想替换它。

可能是这样的?

 middle = ? # (I don't know how to get the middle of a string)

if str[middle] != char:
    str[middle].replace('')

原文由 Jordan Baron 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 500
1 个回答

由于字符串在 Python 中是 不可变 的,因此只需创建一个新字符串,其中包含所需索引处的值。

假设你有一个字符串 s ,也许 s = "mystring"

您可以通过将其放置在原始“切片”之间来快速(并且显然)替换所需索引处的部分。

 s = s[:index] + newstring + s[index + 1:]

您可以通过将字符串长度除以 2 来找到中间位置 len(s)/2

如果你得到神秘的输入,你应该注意处理超出预期范围的索引

def replacer(s, newstring, index, nofail=False):
    # raise an error if index is outside of the string
    if not nofail and index not in range(len(s)):
        raise ValueError("index outside given string")

    # if not erroring, but the index is still not in the correct range..
    if index < 0:  # add it to the beginning
        return newstring + s
    if index > len(s):  # add it to the end
        return s + newstring

    # insert the new string between "slices" of the original
    return s[:index] + newstring + s[index + 1:]

这将作为

replacer("mystring", "12", 4)
'myst12ing'

原文由 ti7 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题