【问题标题】:Modifying a string multiple times based on dict根据dict多次修改字符串
【发布时间】:2021-10-21 00:16:37
【问题描述】:

小例子:

代码

s = "A or B and C"
d = {"A": "1", "B": "0", "C": "0"}

for key, value in d.items():
    s = s.replace(key, value)

print(s)

输出

1 or 0 and 0

此代码产生所需的输出,但我确实觉得有一个聪明的单线可以代替我的循环。

【问题讨论】:

  • 你可以使用str.translate,但老实说我建议保留这段代码。
  • s.translate(s.maketrans(d)) 确实有效,但我认为循环看起来也更干净。谢谢!
  • 不要回答问题。

标签: python string dictionary


【解决方案1】:

虽然我建议保持您的代码不变:

s = "A or B and C"
d = {"A": "1", "B": "0", "C": "0"}

print(s.translate(s.maketrans(d)))

输出:

1 or 0 and 0

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 2016-07-07
    • 2012-01-19
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2016-05-08
    • 2020-06-15
    • 2018-02-06
    相关资源
    最近更新 更多