[Python] Use a python regex expression to replace spaces between words in string1 with...

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

  1. Stack

    Stack Membro Participativo

    I want to use a Python regex replacement operation to change prospective file names such as

    Using 3 Buttons in PyQt5 DialogButtonBox into

    Using_3_Buttons_in_PyQt5_DialogButtonBox_aaa.pdf

    If I only wanted to replace the spaces with "_", the replacement operation would be trivial and could be solved with the following lines:

    string1 = "Using 3 Buttons in PyQt5 DialogButtonBox"
    string1_revised = re.sub('[ ]', '_', string1)


    If I wanted to only add '_aaa.pdf' to the end of string1, the operation again would trivial:

    result2 = re.sub('(?P<wholeThing>.+)', '\g<wholeThing>_aaa.pdf', string1)

    But I want the replacement operation to replace the spaces with underscores, and add "_aaa.pdf" to the end of string1_revised.

    I think the following expression matches string1, and assigns the group name "wholeThing" to string1: (?P<wholeThing>(([A-Za-z0-9]+)([ ]))(x)?)

    But I can't figure out how to code the replacement. Any insights would be much appreciated. Thank you. Marc

    Continue reading...

Compartilhe esta Página