旧字符串格式的Python替代方案
我只是尝试在包含许多随机大括号的文本上使用Python的旧字符串格式的Python替代方案,python,Python,我只是尝试在包含许多随机大括号的文本上使用Python的.format()。它不起作用,因为.format()试图替换单个花括号内的所有内容。在读了一些书之后,我似乎有三个坏的选择: 把那些随机的大括号翻一番——这看起来很难看 使用旧的字符串格式%-这似乎已经过时了 导入一个模板引擎-这似乎有些过分 最好的选择是什么?有更好的选择吗?这里有一个简单的方法: >>> my_string = "Here come the braces : {a{b}c}d{e}f" >>
.format()
。它不起作用,因为.format()
试图替换单个花括号内的所有内容。在读了一些书之后,我似乎有三个坏的选择:
%
-这似乎已经过时了最好的选择是什么?有更好的选择吗?这里有一个简单的方法:
>>> my_string = "Here come the braces : {a{b}c}d{e}f"
>>> additional_content = " : {}"
>>> additional_content = additional_content.format(42)
>>> my_string += additional_content
>>> my_string
'Here come the braces : {a{b}c}d{e}f : 42'
此外,还可以创建一个函数,使大括号加倍:
def double_brace(string):
string = string.replace('{','{{')
string = string.replace('}','}}')
return string
my_string = "Here come the braces : {a{b}c}d{e}f"
my_string = double_brace(my_string)
my_string += " : {}"
my_string = my_string.format(42)
print(my_string)
输出:
>>> Here come the braces : {a{b}c}d{e}f : 42
问自己一个非常重要的问题。你需要
.format()
做什么?%
真的被大幅贬值了吗?我仍然可以看到它的用户在我身边@。你可以插入%s
等等,然后替换它。也许.replace()是我最好的选择?我可以编辑这个问题,把它也包括在内。标准库中有一个。