'in-place' string modifications in Python

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

    Here is an example using translate to switch "-" with "." and uppercase "a"s

    >>> from string import maketrans
    >>> trans_table = maketrans(".-a","-.A")
    >>> "foo-bar.".translate(trans_table)
    'foo.bAr-'
    

    This is much more efficient that flipping to byte array and back if you just need to do single char replacements

提交回复
热议问题