简体   繁体   中英

Replacing one character of a string in python

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

TypeError: 'str' object 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 ie 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

用这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM