'in-place' string modifications in Python

后端 未结 14 1455
一整个雨季
一整个雨季 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)
    
    0 讨论(0)
  • 2020-12-06 00:03

    I'd say the most Pythonic way is to use map():

    s = map(func, s) # func has been applied to every character in s
    

    This is the equivalent of writing:

    s = "".join(func(c) for c in s)
    
    0 讨论(0)
  • 2020-12-06 00:03

    string.translate is probably the closest function to what you're after.

    0 讨论(0)
  • 2020-12-06 00:03
    >>> mystring = "Th1s 1s my str1ng"
    >>> mystring.replace("1", "i")
    'This is my string'
    

    If you want to store this new string you'll have to mystring = mystring.replace("1", "i"). This is because in Python strings are immutable.

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

    I did that like this:

    import tempfile
    import shutil
    
    ...
    
    f_old = open(input_file, 'r')
    with tempfile.NamedTemporaryFile() as tmp:
        for line in f_old:
            tmp.write(line.replace(old_string, new_string))
        f_old.close()
        tmp.flush()
        os.fsync(tmp)
        shutil.copy2(tmp.name, input_file)
        tmp.close()
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题