Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据字符在字符串python中的位置更改字符_Python_String_Position_Numeric - Fatal编程技术网

如何根据字符在字符串python中的位置更改字符

如何根据字符在字符串python中的位置更改字符,python,string,position,numeric,Python,String,Position,Numeric,我想做一个刽子手游戏,我需要改变字符串中的某些字符。 例如:“----”,我想用一个字母改变这个字符串的第三个破折号。这需要处理任意长度的单词,如有任何帮助,将不胜感激。字符串是不可变的,请将其列为一个列表,然后替换字符,然后将其返回为如下所示的字符串: s = '-----' s = list(s) s[2] = 'a' s = ''.join(s) 也会起作用。我不确定哪一个(有.join的和没有.join的)更有效 >>> a 'this is really strin

我想做一个刽子手游戏,我需要改变字符串中的某些字符。
例如:“----”,我想用一个字母改变这个字符串的第三个破折号。这需要处理任意长度的单词,如有任何帮助,将不胜感激。

字符串是不可变的,请将其列为一个列表,然后替换字符,然后将其返回为如下所示的字符串:

s = '-----'
s = list(s)
s[2] = 'a'
s = ''.join(s)

也会起作用。我不确定哪一个(有.join的和没有.join的)更有效

>>> a
'this is really string'
>>> a[:2]+'X'+a[3:]
'thXs is really string'
>>> 

请看:@j.f.是正确的。与Java或C不同,Python中不能更改字符串。您应该将字符串转换为列表,然后可以逐个字符修改该列表。这就是我最后使用的字符串。谢谢:D
>>> a
'this is really string'
>>> a[:2]+'X'+a[3:]
'thXs is really string'
>>>