【发布时间】:2017-06-04 19:27:12
【问题描述】:
如何从某个索引替换字符串中的字符?比如我想从一个字符串中获取中间字符,比如abc,如果这个字符不等于用户指定的字符,那么我想替换它。
可能是这样的吗?
middle = ? # (I don't know how to get the middle of a string)
if str[middle] != char:
str[middle].replace('')
【问题讨论】:
-
字符串是不可变的,你需要创建一个新的字符串。格式为
slice_before_index + char + slice_after_index。 -
python 中的字符串是不可变的...这意味着你必须构造一个新字符串
-
这能回答你的问题吗? Changing one character in a string in Python
-
时间比较,查看这个答案:stackoverflow.com/questions/1228299/…
标签: python python-3.x string