给定字符串替换子字符串,将字符串替换为键,替换为值.蟒蛇

alv*_*vas 0 python string dictionary replace

我与一个字典字符串被替换keys和它更换为值.除了通过令牌查看字符串令牌之外,还有更好/更快的替换方法吗?

我一直在这样做:

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}

sentence = "this is a foobar in a barbar withoutspace"

for i in sentence.split():
  if i in segmenter:
    sentence.replace(i, segmenter[i])
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 5

字符串在python中是不可变的.因此,str.replace返回一个新字符串而不是修改原始字符串.你可以str.join()在这里使用和列出理解:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

另外一个问题str.replace是,它还将取代的话就像"abarbarb"

"abar barb".