'in-place' string modifications in Python

后端 未结 14 1522
一整个雨季
一整个雨季 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:01

    If I ever need to do something like that I just convert it to a mutable list

    For example... (though it would be easier to use sort (see second example) )

    >>> s = "abcdfe"
    >>> s = list(s)
    >>> s[4] = "e"
    >>> s[5] = "f"
    >>> s = ''.join(s)
    >>> print s
    abcdef
    >>>
    # second example
    >>> s.sort()
    >>> s = ''.join(s)
    

提交回复
热议问题