Python 中的字符串替换列表 [英] A list of string replacements in Python

查看:54
本文介绍了Python 中的字符串替换列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更短的方法来编写以下代码?

Is there a far shorter way to write the following code?

my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')

请注意,我不需要替换那些确切的值;我只是在寻找一种将 5+ 行变成少于 5 行的方法

Note that I don't need those exact values replaced; I'm simply looking for a way to turn 5+ lines into fewer than 5

推荐答案

看起来是使用循环的好机会:

Looks like a good opportunity to use a loop:

mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
    my_string = my_string.replace(k, v)

如果您不介意括号,一个更快的方法是:

A faster approach if you don't mind the parentheses would be:

mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
    my_string = my_string.replace(k, v)

这篇关于Python 中的字符串替换列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆