How do I modify a single character in a string, in Python?

前端 未结 4 1849
傲寒
傲寒 2020-12-16 13:54

How do I modify a single character in a string, in Python? Something like:

 a = \"hello\"
 a[2] = \"m\"

\'str\' object does not support ite

相关标签:
4条回答
  • 2020-12-16 14:00

    In python, string are immutable. If you want to change a single character, you'll have to use slicing:

    a = "hello"
    a = a[:2] + "m" + a[3:]
    
    0 讨论(0)
  • 2020-12-16 14:00

    Try constructing a list from it. When you pass an iterable into a list constructor, it will turn it into a list (this is a bit of an oversimplification, but usually works).

    a = list("hello")
    a[2] = m
    

    You can then join it back up with ''.join(a).

    0 讨论(0)
  • 2020-12-16 14:16

    It's because strings in python are immutable.

    0 讨论(0)
  • 2020-12-16 14:22

    Strings are immutable in Python. You can use a list of characters instead:

    a = list("hello")
    

    When you want to display the result use ''.join(a):

    a[2] = 'm'
    print ''.join(a)
    
    0 讨论(0)
提交回复
热议问题