[Python] How to replace *all* occurrences of a string in Python, and why `str.replace` misses...

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    I want to replace all patterns 0 in a string by 00 in Python. For example, turning:

    '28 5A 31 34 0 0 0 F0'

    into

    '28 5A 31 34 00 00 00 F0'.

    I tried with str.replace(), but for some reason it misses some "overlapping" patterns: i.e.:

    $ python3
    Python 3.12.3 (main, Feb 4 2025, 14:48:35) [GCC 13.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> '28 5A 31 34 0 0 0 F0'.replace(" 0 ", " 00 ")
    '28 5A 31 34 00 0 00 F0'
    >>> '28 5A 31 34 0 0 0 F0'.replace(" 0 ", " 00 ").replace(" 0 ", " 00 ")
    '28 5A 31 34 00 00 00 F0'


    notice the "middle" 0 pattern that is not replaced by 00.

    • Any idea how I could replace all patterns at once? Of course I can do '28 5A 31 34 0 0 0 F0'.replace(" 0 ", " 00 ").replace(" 0 ", " 00 "), but this is a bit heavy...
    • I actually did not expect this behavior (found it through a bug in my code). In particular, I did not expect this behavior from the documentation at https://docs.python.org/3/library/stdtypes.html#str.replace . Any explanation to why this happens / anything that should have tipped me that this is the expected behavior? It looks like replace does not work with consecutive overlapping repetitions of the pattern, but this was not obvious to me from the documentation?

    Edit 1:

    Thanks for the answer(s). The regexp works nicely.

    Still, I am confused. The official doc linked above says:


    "Return a copy of the string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced. If count is not specified or -1, then all occurrences are replaced.".
    ​

    "Clearly" this is not the case? (or am I missing something?).

    Continue reading...

Compartilhe esta Página