将项目分配用于python字符串的最佳/正确方法是什么?
即s = "ABCDEFGH" s[1] = 'a' s[-1]='b'?
s = "ABCDEFGH"
s[1] = 'a'
s[-1]='b'
正常方式会抛出: 'str' object does not support item assignment
'str' object does not support item assignment
字符串是不可变的。这意味着您根本无法分配给他们。您可以使用格式:
>>> s = 'abc{0}efg'.format('d') >>> s 'abcdefg'
或串联:
>>> s = 'abc' + 'd' + 'efg' >>> s 'abcdefg'
或更换(感谢Odomontois提醒我):
>>> s = 'abc0efg' >>> s.replace('0', 'd') 'abcdefg'
但是请记住,所有这些方法都将创建字符串的 副本 ,而不是就地对其进行修改。如果要进行就地修改,可以使用bytearray-,尽管这仅适用于纯ascii字符串,正如Alexis指出的那样。
bytearray
>>> b = bytearray('abc0efg') >>> b[3] = 'd' >>> b bytearray(b'abcdefg')
或者,您可以创建一个字符列表并进行操作。这可能是频繁,大规模字符串处理的最有效和正确的方法:
>>> l = list('abc0efg') >>> l[3] = 'd' >>> l ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> ''.join(l) 'abcdefg'
并考虑将re模块用于更复杂的操作。
re
字符串格式化和列表操作是最有可能是正确且有效的IMO的两种方法-仅需要少量插入时进行字符串格式化,而在需要频繁更新字符串时进行列表操作。