[Python] How can I replace multiple items in a string using a dictionary when the matched...

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    Given this dictionary and input strings:

    d = { 'one': '1',
    'two': '2',
    'three': '3'
    }

    s1 = 'String containing <#one|> or <#two|> numbers. <#one|>, <#two|>, <#three|>'
    s2 = 'Only replace items which are anchored. <#one|> is replaced, but not this one.'


    How can I replace each occurrence of an anchored item <# |> using the dictionary d? The above strings should produce the output:

    String containing 1 or 2 numbers. 1, 2, 3
    Only replace items which are anchored. 1 is replaced, but not this one.


    Using single pass multi replacement described here comes close to solving this, but doesn't handle the anchors.

    Continue reading...

Compartilhe esta Página