如何在 Python 中修改字符串中的单个字符? [英] How do I modify a single character in a string, in Python?
本文介绍了如何在 Python 中修改字符串中的单个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 中修改字符串中的单个字符?类似的东西:
How do I modify a single character in a string, in Python? Something like:
a = "hello"
a[2] = "m"
'str' 对象不支持项目分配.
'str' object does not support item assignment.
推荐答案
字符串在 Python 中是不可变的.您可以改用字符列表:
Strings are immutable in Python. You can use a list of characters instead:
a = list("hello")
当你想显示结果时使用 ''.join(a)
:
When you want to display the result use ''.join(a)
:
a[2] = 'm'
print ''.join(a)
这篇关于如何在 Python 中修改字符串中的单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文