'in-place' string modifications in Python

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

    Assigning a particular character to a particular index in a string is not a particularly common operation, so if you find yourself needing to do it, think about whether there may be a better way to accomplish the task. But if you do need to, probably the most standard way would be to convert the string to a list, make your modifications, and then convert it back to a string.

    s = 'abcdefgh'
    l = list(s)
    l[3] = 'r'
    s2 = ''.join(l)
    

    EDIT: As posted in bstpierre's answer, bytearray is probably even better for this task than list, as long as you're not working with Unicode strings.

    s = 'abcdefgh'
    b = bytearray(s)
    b[3] = 'r'
    s2 = str(b)
    

提交回复
热议问题