Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python

前端 未结 2 1635
夕颜
夕颜 2021-01-17 05:56

I have a dictionary with the strings to be replaced as keys and its replacement as values. Other than looking through the stri

2条回答
  •  难免孤独
    2021-01-17 06:23

    String are immutable in python. So, str.replace returns a new string instead of modifying the original string. You can use str.join() and list comprehension here:

    >>> segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
    >>> sentence = "this is a foobar in a barbar withoutspace"
    
    >>> " ".join( [ segmenter.get(word,word) for word in sentence.split()] )
    'this is a foo bar in a bar bar without space'
    

    Another problem with str.replace is that it'll also replace words like "abarbarb" with

    "abar barb".

提交回复
热议问题