本文主要是介绍Python string modify,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
How do I modify a string in place?
You can’t, because strings are immutable. Most string manipulation code in Python simply creates new strings instead of modifying the existing ones.
If you need a string-like object that can be modified in place, try converting the string to a list or use the array module:
>>> s = "Hello, world"
>>> a = list(s)
>>> print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> a[7:] = list("there!")
>>> ''.join(a)
'Hello, there!'>>> import array
>>> a = array.array('c', s)
>>> print a
array('c', 'Hello, world')
>>> a[0] = 'y' ; print a
array('c', 'yello world')
>>> a.tostring()
'yello, world'
CATEGORY: programming
这篇关于Python string modify的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!