'in-place' string modifications in Python

后端 未结 14 1513
一整个雨季
一整个雨季 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-05 23:48

    Strings are iterable and can be walked through like lists. Strings also have a number of basic methods such as .replace() that might be what you're looking for. All string methods return a new string. So instead of modifying the string in place you can simply replace its existing value.

    >>> mystring = 'robot drama'
    >>> mystring = mystring.replace('r', 'g')
    >>> mystring
    'gobot dgama'
    

提交回复
热议问题