1

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

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"]

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

有没有解决的办法?

4

2 回答 2

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'
于 2013-04-15T06:00:21.473 回答
-1

不完全完美,但如果只有几个你想替换你可以在搜索字母时包含空格,即:

b = {"u ":"i", "c ":"see", "me ":"you"," u ":"i", " c ":"see", " me ":"you",
     " u":"i", " c":"see", "me ":"you"}
于 2013-04-15T06:01:15.103 回答