你能在 Python 中使用字典值写一个 str.replace() 吗? [英] can you write a str.replace() using dictionary values in Python?
本文介绍了你能在 Python 中使用字典值写一个 str.replace() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在地址字段中用 N S 替换北、南等.
I have to replace the north, south, etc with N S in address fields.
如果我有
list = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address = "123 north anywhere street"
我可以迭代我的字典值来替换我的地址字段吗?
Can I for iterate over my dictionary values to replace my address field?
for dir in list[]:
address.upper().replace(key,value)
我知道我什至不接近!!但是,如果您可以使用这样的字典值,我们将不胜感激.
I know i'm not even close!! But any input would be appreciated if you can use dictionary values like this.
推荐答案
address = "123 north anywhere street"
for word, initial in {"NORTH":"N", "SOUTH":"S" }.items():
address = address.replace(word.lower(), initial)
print address
漂亮、简洁且可读.
这篇关于你能在 Python 中使用字典值写一个 str.replace() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文