python - 替代 python 替换

标签 python

我想知道下面的代码是否有替代方案,因为 1:有错误,2:我不想经常这样做:

restring=string.replace("a","01").replace("b","02")...

可能替换的代码:

chars=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","t","s","u","v","w","x","y","z"]
numbs=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
string="test";
restring=string.replace(chars,numbs);
print restring;

最佳答案

在这里,由于您只有 1 个字符替换“键”,因此我将使用字典和 join:

>>> chars=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","t","s","u","v","w","x","y","z"]
>>> numbs=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
>>> d = dict(zip(chars,numbs))
>>> my_sentence = "foobar"
>>> ''.join(d.get(c,c) for c in my_sentence)
'061515020118'

这并不能扩展到多个字符替换键......

关于python - 替代 python 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302793/

相关文章:

python - numpy.r_ 不是函数。它是什么?

python - 如何运行创建一个discord.py机器人命令,该命令将使用不同的参数多次运行另一个机器人命令?

python - 将 Python 列表转换为 Pandas 系列

python - Wing IDE 调试服务器在探测本地时遇到错误

python - 相同对象的缓慢相等评估 (x == x)

python - 如何将反斜杠转换为正斜杠?

python - 使用 Pandas 将相似的条目分组并合并在一起

python - 已安装 Python 模块上的 ImportError

python - 如何匹配字符串中的日期模式

python - 不和谐的python机器人离开命令不起作用