Replacing one character of a string in python

后端 未结 5 1022
傲寒
傲寒 2020-12-20 11:35

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

TypeError: \'str\' object does not support item assig

相关标签:
5条回答
  • 2020-12-20 12:19
    >>> import ctypes
    >>> s = "1234567890"
    >>> mutable = ctypes.create_string_buffer(s)
    >>> mutable[3] = "a"
    >>> print mutable.value
    123a567890
    
    0 讨论(0)
  • 2020-12-20 12:21

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

    a = str.replace(str[n],"")
     return a
    
    0 讨论(0)
  • 2020-12-20 12:27

    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.

    0 讨论(0)
  • 2020-12-20 12:32

    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.

    0 讨论(0)
  • 2020-12-20 12:36

    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.

    0 讨论(0)
提交回复
热议问题