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

时间:2013-05-13 07:14:29

标签: 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])

2 个答案:

答案 0 :(得分: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'

str.replace的另一个问题是,它还会将"abarbarb"等字词替换为

"abar barb"

答案 1 :(得分:4)

re.sub可以调用返回替换的函数

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
sentence = "this is a foobar in a barbar withoutspace"

import re

def fn(match):
    return segmenter[match.group()]

print re.sub('|'.join(re.escape(k) for k in segmenter), fn, sentence)