python使用iteritems()替换字符串中的某些字母/单词

时间:2013-04-15 05:51:03

标签: python

所以我有代码用其他人替换字符串中的某些字母/单词

c = {"u":"i", "c":"see", "me":"you"}

for a,b in c.iteritems():
        response = response.replace(a,b)

这会将["u c me"]变为["i see you"]
但也将["uncalled"]变为["inseealled"]

我只想更改第一个字符串,但保留第二个字符串

有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

>>> d = {"u":"i", "c":"see", "me":"you"}
>>> ' '.join(d.get(word, word) for word in "u c me".split())
'i see you'
>>> ' '.join(d.get(word, word) for word in "uncalled".split())
'uncalled'

>>> d = {'me': 'you', 'c': 'see', 'u': 'i', 'are': 'am'}
>>> ' '.join(d.get(word, word) for word in "u are big".split())
'i am big'
>>> ' '.join(d.get(word, word) for word in "unique".split())
'unique'

答案 1 :(得分:-1)

不完美但是如果只有少数你想要替换,你可以在搜索字母时包含空格,即:

b = {"u ":"i", "c ":"see", "me ":"you"," u ":"i", " c ":"see", " me ":"you",
     " u":"i", " c":"see", "me ":"you"}