无法工作的示例:
print(" \{ Hello \} {0} ".format(42))
期望得到的输出:
{Hello} 42
无法工作的示例:
print(" \{ Hello \} {0} ".format(42))
期望得到的输出:
{Hello} 42
如果需要在字符串中包含两个花括号,那么变量的每侧都需要有5个花括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
format()
和f-strings之间大括号的行为没有区别。代码 a = 1; print('{{{{{a}}}}}'.format(a=a))
和 a = 1; print(f'{{{{{a}}}}}')
会产生相同的结果。 - Kerrick Staleydef 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}'
最近我遇到了这个问题,因为我想把字符串注入到预格式化的JSON中。 我的解决方案是创建一个帮助方法,像这样:
def preformat(msg):
""" allow {{key}} to be used for formatting in text
that already uses curly braces. First switch this into
something else, replace curlies with double curlies, and then
switch back to regular braces
"""
msg = msg.replace('{{', '<<<').replace('}}', '>>>')
msg = msg.replace('{', '{{').replace('}', '}}')
msg = msg.replace('<<<', '{').replace('>>>', '}')
return msg
您可以执行以下操作:
formatted = preformat("""
{
"foo": "{{bar}}"
}""").format(bar="gas")
如果性能不是问题,那么它可以完成工作。
<<<
和>>>
,否则这些将被覆盖。最好使用转义策略以确保可靠性! - axolotlQQX
);2)将该序列用作变量占位符QQX<name>
;3)进行正则表达式替换以将占位符转换为预期格式(例如)r'QQ<([^>]+)>','{$1}'
。另请参阅: perl quotelike operator - dreftymac原因是,{}
是 .format()
语法的一部分,所以在你的情况下,.format()
不识别 {Hello}
,因此抛出错误。
您可以通过使用双大括号{{}}来覆盖它,
x = " {{ Hello }} {0} "
或者
尝试使用%s
进行文本格式化。
x = " { Hello } %s"
print x%(42)
我来晚了。我尝试将括号放在替换元素中,像这样:
print('{0} {1}'.format('{hello}', '{world}'))
打印输出
{hello} {world}
严格来说,这并不是 OP 所要求的,因为他/她想要在格式字符串中保留括号,但这可能会对某些人有所帮助。
print("{} {}".format("{hello}", "{world}"))
也可以工作。 - ankit我使用双重{{ }}来防止fstring值注入,
例如,这是我的Postgres UPDATE语句,用于更新一个整数数组列,该列采用表达式{}来捕获数组,即:
ports = '{100,200,300}'
使用fstrings,则为:
ports = [1,2,3]
query = f"""
UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""
实际查询语句将是:
UPDATE table SET ports = '{1,2,3}'
这是一个有效的PostgreSQL语句
print(f"{Hello} {42}")
到
print("{Hello}"f" {42}")
string = 10
print(f"{string} {word}")
输出:
NameError: name 'word' is not defined
现在,像这样添加引用墙:
string = 10
print(f"{string}"" {word}")
输出:
10 {word}
我在尝试打印可以复制粘贴到Latex文档中的文本时遇到了这个问题。我扩展了this answer并使用了命名替换字段:
假设您想打印出多个带有索引的变量的乘积,例如,在Latex中将是$A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$
。下面的代码使用命名字段来完成任务,以便对于许多索引,它保持可读性:
idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))
a=3
print(f'{"{"}{a}')
>>> {3
{
加倍仍然足够。因此,可以写成 f'{{{a}'
。 - user202729如果你想要只打印一个花括号(例如{
),你可以使用{{
,并且如果需要的话,你可以在字符串中添加更多的花括号。例如:
>>> 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'
{{ }}
) 的人可以使用string.Template
。在那里,您可以替换形式为$foo
的标识符(方便生成 LaTeX 代码)。 - 0 _