Replace all the occurrences of specific words

前端 未结 4 1850
暗喜
暗喜 2020-12-11 02:00

Suppose that I have the following sentence:

bean likes to sell his beans

and I want to replace all occurrences of specific words with other

4条回答
  •  没有蜡笔的小新
    2020-12-11 02:18

    If you use regex, you can specify word boundaries with \b:

    import re
    
    sentence = 'bean likes to sell his beans'
    
    sentence = re.sub(r'\bbean\b', 'robert', sentence)
    # 'robert likes to sell his beans'
    

    Here 'beans' is not changed (to 'roberts') because the 's' on the end is not a boundary between words: \b matches the empty string, but only at the beginning or end of a word.

    The second replacement for completeness:

    sentence = re.sub(r'\bbeans\b', 'cars', sentence)
    # 'robert likes to sell his cars'
    

提交回复
热议问题