'in-place' string modifications in Python

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

    You can use StringIO class to receive file-like mutable interface of string.

    0 讨论(0)
  • 2020-12-06 00:08

    Don't use a string, use something mutable like bytearray:

    #!/usr/bin/python
    
    s = bytearray("my dog has fleas")
    for n in xrange(len(s)):
        s[n] = chr(s[n]).upper()
    print s
    

    Results in:

    MY DOG HAS FLEAS
    

    Edit:

    Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:

    s = bytearray("\x81\x82\x83")
    for n in xrange(len(s)):
        s[n] = s[n] + 1
    print repr(s)
    

    gives:

    bytearray(b'\x82\x83\x84')
    

    If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.

    0 讨论(0)
提交回复
热议问题