'in-place' string modifications in Python

后端 未结 14 1517
一整个雨季
一整个雨季 2020-12-05 23:38

In Python, strings are immutable.

What is the standard idiom to walk through a string character-by-character and modify it?

The only methods I can think of a

14条回答
  •  借酒劲吻你
    2020-12-06 00:03

    >>> mystring = "Th1s 1s my str1ng"
    >>> mystring.replace("1", "i")
    'This is my string'
    

    If you want to store this new string you'll have to mystring = mystring.replace("1", "i"). This is because in Python strings are immutable.

提交回复
热议问题