Python中旧字符串格式化的替代方法

3
我刚试用Python的.format()来格式化包含很多随机花括号的文本,但它失败了,因为.format()尝试替换单个花括号内的所有内容。经过一些阅读,好像我有三个不好的选择:
  1. 将所有随机花括号加倍 - 这看起来不美观
  2. 使用旧式字符串格式化% - 这似乎已经过时了
  3. 导入一个模板引擎 - 这似乎有点大材小用
什么是最佳选择?有更好的选择吗?

4
请问你自己一个非常重要的问题:你需要.format()做什么? - Tadeck
“%” 真的被强烈废弃了吗?我仍然能看到周围有人在使用它 @@。 - Jokester
1
你可以插入%s等内容并进行替换。 - Waleed Khan
也许 .replace() 是我最好的选择?我可以编辑问题并包含它。 - benshope
2
标准库中有一个简单的模板引擎。 - fjarri
1个回答

1
这里有一个简单的方法:
>>> 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接