所以我有代码可以用其他字母/单词替换字符串中的某些字母/单词
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"]
我只想更改第一个字符串,但保留第二个字符串相同
有没有解决的办法?
所以我有代码可以用其他字母/单词替换字符串中的某些字母/单词
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"]
我只想更改第一个字符串,但保留第二个字符串相同
有没有解决的办法?
>>> 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'
不完全完美,但如果只有几个你想替换你可以在搜索字母时包含空格,即:
b = {"u ":"i", "c ":"see", "me ":"you"," u ":"i", " c ":"see", " me ":"you",
" u":"i", " c":"see", "me ":"you"}