[Python] Python regex replacement with str.replace. Pattern (wordhypenword) Replacement...

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following regex pattern word-word, so

    r'\w+\-\w+


    I would like to replace it with

    r'\w+\s\-\s\w+


    Example: I would like to change

    hello-friends to hello - friends


    I have tried the following with no success

    df['mytextcolumn'].str.replace(r'(\\w+)(\\-)(\\w+)',r'(\\w+)(\\s)(\\-)(\\s)(\\w+)')



    also tried with re.sub

    re.sub(r'\\w+\\-\\w+',r'\\w+\\s\\-\\s\\w+','hello-friends')

    but I still get back hello-friends, not hello - friends


    I also checked my regex with an online regex matcher for python, and it picks up the patterns correctly, so I am confused why I am unable to replace it within my script.

    Continue reading...

Compartilhe esta Página