在Python的字典中搜索并替换值(字符串)

问题描述 投票:-3回答:1

让我们列出以下词典:

my_example=[{'part': '"Is this a Text? Yes"', 'supplement': '123'},{'part': '"This is the right text: Yes"', 'supplement': '123'},{'part': '"This is the right text: Yes"', 'supplement': '123'}

我想用一个冒号替换问号,即如果有一个“?”,则该值将通过替换“?”来更改。带有“:”。我曾考虑过使用my_example.get,但仍然无法替换。

任何想法?

python dictionary search replace
1个回答
0
投票

您可以使用列表理解:

[{k: v.replace('?', ':') for k, v in d.items()} for d in my_example]

输出:

[{'part': '"Is this a Text: Yes"', 'supplement': '123'},
 {'part': '"This is the right text: Yes"', 'supplement': '123'},
 {'part': '"This is the right text: Yes"', 'supplement': '123'}]
© www.soinside.com 2019 - 2024. All rights reserved.