非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
如果在可以格式化的f-string模板中需要大括号,则需要在f-string的一组大括号中输出包含两个大括号的字符串:
css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'
其他回答
试试看:
x=“{{你好}}{0}”
如果只想打印一个大括号(例如{),可以使用{{,如果需要,可以稍后在字符串中添加更多大括号。例如:
>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'
我参加这个聚会迟到了,真是可笑。我成功地将支架放置在替换元件中,如下所示:
print('{0} {1}'.format('{hello}', '{world}'))
打印
{hello} {world}
严格地说,这不是OP所要求的,因为他/她希望格式字符串中包含大括号,但这可能会对某人有所帮助。
Python 3.6+(2017)
在最近的Python版本中,可以使用f-string(另请参见PEP498)。
对于f字符串,应该使用双{{或}}
n = 42
print(f" {{Hello}} {n} ")
产生所需的
{Hello} 42
如果需要解析括号中的表达式而不是使用文本,则需要三组括号:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
生产
{hello}
如果你要经常这样做,最好定义一个实用函数,让你使用任意的大括号替代,比如
def custom_format(string, brackets, *args, **kwargs):
if len(brackets) != 2:
raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
padded = string.replace('{', '{{').replace('}', '}}')
substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
formatted = substituted.format(*args, **kwargs)
return formatted
>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'
注意,这将在括号是长度为2的字符串或两个字符串的可迭代(对于多字符分隔符)的情况下工作。