如何转义格式字符串? [英] How can I escape the format string?

查看:39
本文介绍了如何转义格式字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Python 的 str.format(key=value) 语法来仅替换某些键.

Is it possible to use Python's str.format(key=value) syntax to replace only certain keys.

考虑这个例子:

my_string = 'Hello {name}, my name is {my_name}!'

my_string = my_string.format(name='minerz029')

哪个返回

KeyError: 'my_name'

有没有办法做到这一点?

Is there a way to achieve this?

推荐答案

我使用的一些更简单的解决方法:

A bit of a simpler workaround which I use:

my_string = 'Hello {name}, my name is {my_name}!'

to_replace = {
    "search_for" : "replace_with",
    "name" : "minerz029",
}

for search_str in to_replace:
    my_string = my_string.replace('{' + search_str + '}', to_replace[search_str])

print(my_string)

这可以通过 to_replace 字典中的更多键轻松扩展,即使搜索字符串不存在也不会抱怨.可能可以改进以提供更多 .format() 的功能,但这对我来说已经足够了.

This can be expanded easily with more keys in the to_replace dict and wont complain even if the search string doesn't exist. It could probably be improved to offer more of .format()'s features, but it was enough for me.

这篇关于如何转义格式字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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