Replace spaces with underscores but not all of them

前端 未结 1 484
野性不改
野性不改 2021-01-21 17:43

I\'m pretty new to Python, but we are working on cleaning up some text files, and, among others, I will need to do the following: Replace spaces with underscores, but only in so

相关标签:
1条回答
  • 2021-01-21 18:43

    Use re.sub with a lambda:

    x = re.sub(r'/2.*?/1', lambda x: re.sub(r'\s+', '_', x.group()), x)
    

    Match all strings between /2 and /1 and replace whitespace strings only there with the nested re.sub.

    0 讨论(0)
提交回复
热议问题