Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python -
i have dictionary strings replaced keys
, replacement values. other looking through strings token token, there better/faster way of doing replacement?
i've been doing such:
segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'} sentence = "this foobar in barbar withoutspace" in sentence.split(): if in segmenter: sentence.replace(i, segmenter[i])
string immutable in python. so, str.replace
returns new string instead of modifying original string. can use str.join()
, list comprehension here:
>>> segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'} >>> sentence = "this foobar in barbar withoutspace" >>> " ".join( [ segmenter.get(word,word) word in sentence.split()] ) 'this foo bar in bar bar without space'
another problem str.replace
it'll replace words "abarbarb"
"abar barb"
.
Comments
Post a Comment