如何一次进行多个替换?|python
我有以下字符串:如何一次进行多个替换?|python,python,python-3.x,string,replace,Python,Python 3.x,String,Replace,我有以下字符串: stringone = '0123456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS' 我需要做以下工作: 0 = s 1 = 6 2 = r ... Z = F 但我需要马上做。我是说,不是 stringone.replace('0', 's') stringone.replace('1', '6') …不是那样,而是一行。比如说,我能做吗 stringone.replace('0', 's'; '1
stringone = '0123456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS'
我需要做以下工作:
0 = s
1 = 6
2 = r
...
Z = F
但我需要马上做。我是说,不是
stringone.replace('0', 's')
stringone.replace('1', '6')
…不是那样,而是一行。比如说,我能做吗
stringone.replace('0', 's'; '1', '6')
我不知道怎么做。你能帮助我吗?
Python 3.6.0让我们用字典来实现这一点:
dic = {'0':'s', '1':'6', '2':'r'....}
# either join
''.join(i if i not in dic else dic[i] for i in stringone)
# or re
import re
re.compile("|".join(dic.keys())).sub(lambda m: dic[re.escape(m.group(0))], stringone)
Join更简单,因为我们用值替换键。>stringone.translate({ord('0'):'s',ord('1'):'6'))
's623456789 ABCDEFGHIJKLMNOPQRSTUVXYS ABCDEFGHIJKLMNOPQRSTUVXYS'
尝试以下方法:
import re
def multireplace(string, sub_dict):
substrings = sorted(sub_dict, key=len, reverse=True)
regex = re.compile('|'.join(map(re.escape, substrings)))
return regex.sub(lambda match: sub_dict[match.group(0)], string)
stringone = '0123456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS'
sub_dict = {"0": "s", "1": "6", "2":"r","Z":"F"}
output = multireplace(stringone, sub_dict)
创建具有要替换的值的元组列表:
elements = [('0', 's'), ('1', '6'), ..., ('Z', 'F')]
然后循环浏览此列表:
for to_replace, replacement in elements:
my_string = my_string.replace(to_replace, replacement)
这回答了你的问题吗?部分是这样,但我没有找到一个适合我的简短代码的答案,在我创建了这篇文章之后,我发现它很简单!我只想再问一个问题:ord在这里是什么意思?ord返回字符的整数代码,因为
str.translate
将这些代码映射到操作。或者,对于这种特定情况,您可以使用stringone.translate(str.maketrans('01','s6'))