开发者

Replacing one character of a string in python

In python, are strings mutable? The line someString[3] = "a" throws the error

TypeError: 'str' obj开发者_如何学JAVAect does not support item assignment

I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?


Python strings are immutable, which means that they do not support item or slice assignment. You'll have to build a new string using i.e. someString[:3] + 'a' + someString[4:] or some other suitable approach.


Instead of storing your value as a string, you could use a list of characters:

>>> l = list('foobar')
>>> l[3] = 'f'
>>> l[5] = 'n'

Then if you want to convert it back to a string to display it, use this:

>>> ''.join(l)
'foofan'

If you are changing a lot of characters one at a time, this method will be considerably faster than building a new string each time you change a character.


In new enough pythons you can also use the builtin bytearray type, which is mutable. See the stdlib documentation. But "new enough" here means 2.6 or up, so that's not necessarily an option.

In older pythons you have to create a fresh str as mentioned above, since those are immutable. That's usually the most readable approach, but sometimes using a different kind of mutable sequence (like a list of characters, or possibly an array.array) makes sense. array.array is a bit clunky though, and usually avoided.


>>> import ctypes
>>> s = "1234567890"
>>> mutable = ctypes.create_string_buffer(s)
>>> mutable[3] = "a"
>>> print mutable.value
123a567890


Use this:

someString.replace(str(list(someString)[3]),"a")


Just define a new string equaling to what you want to do with your current string.

a = str.replace(str[n],"")
 return a
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜