【问题标题】:Python find and replace in string based on a mapping dictionary [duplicate]Python基于映射字典在字符串中查找和替换[重复]
【发布时间】:2021-09-05 13:01:02
【问题描述】:

我有一个字符串

str = "abcdef"

还有一个映射

map = {'a':'b','b':'c', 'c':'d'}

预期的输出是

out_str = 'bcddef'

如何在 python 的一次迭代中应用映射?

【问题讨论】:

    标签: python-3.x string dictionary replace find


    【解决方案1】:

    试试:

    s = "abcdef"
    m = {"a": "b", "b": "c", "c": "d"}
    
    print("".join(m.get(ch, ch) for ch in s))
    

    打印:

    bcddef
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-26
      • 2015-04-25
      • 1970-01-01
      • 2021-10-14
      • 2017-06-03
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      相关资源
      最近更新 更多