Python 如何在字符串中打印文字大括号字符并在其上使用.format?
给我:Python 如何在字符串中打印文字大括号字符并在其上使用.format?,python,string,format,string-formatting,curly-braces,Python,String,Format,String Formatting,Curly Braces,给我:键错误:Hello\\ 我想打印输出:{Hello}42试试这个: x=“{{Hello}}{0}”您可以通过将大括号加倍来转义它 例如: 尝试这样做: x = "{{ Hello }} {0}" print(x.format(42)) >>> x = '{}Hello{} {}' >>> print x.format('{','}',42) {Hello} 42 您需要将{{和}加倍: x = " {{ Hello }} {0} " print x
键错误:Hello\\
我想打印输出:{Hello}42
试试这个:
x=“{{Hello}}{0}”
您可以通过将大括号加倍来转义它
例如:
尝试这样做:
x = "{{ Hello }} {0}"
print(x.format(42))
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
您需要将
{{
和}
加倍:
x = " {{ Hello }} {0} "
print x.format(42)
以下是报告的相关部分:
格式字符串包含由大括号包围的“替换字段”{}
。大括号中不包含的任何内容都被视为文字文本,它会原封不动地复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍来转义:{{
和}
虽然不是更好,但仅供参考,您也可以这样做:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
例如,当有人想要打印{argument}
时,它可能很有用。它可能比'{{}}更可读。格式('argument')
请注意,在Python 2.7之后,您省略了参数位置(例如,
{}
而不是{0}
),OP编写了以下注释:
出于某些目的,我试图格式化一个小JSON,比如:{“all”:false,selected:{}。格式化(数据)
以获得类似于{“all”:false,selected:“1,2”}
在处理JSON时,出现“转义大括号”问题是很常见的
我建议这样做:
x = "{{ Hello }} {0}"
print(x.format(42))
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
它比备选方案更干净,即:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
当json字符串变得比示例更复杂时,使用
json
库无疑是更好的选择。如果您打算经常这样做,那么最好定义一个实用函数,让您可以使用任意大括号替换,如
'{{"all": false, "selected": "{}"}}'.format(data)
请注意,对于长度为2的字符串或由两个字符串组成的iterable(对于多字符分隔符),这将起作用 原因是,
{}
是.format()
的语法,因此在您的情况下,.format()
无法识别{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}'
或
请尝试使用%s
设置文本格式
x = " {{ Hello }} {0} "
Python 3.6+(2017)
在Python的最新版本中,可以使用(另请参见)
对于f字符串,应该使用double{{
或}
x = " { Hello } %s"
print x%(42)
产生所需的结果
n = 42
print(f" {{Hello}} {n} ")
如果需要解析括号中的表达式而不是使用文本,则需要三组括号:
{Hello} 42
产生
hello = "HELLO"
print(f"{{{hello.lower()}}}")
如果需要在字符串中保留两个大括号,则需要在变量的每一侧保留5个大括号
{hello}
您可以使用原始字符串方法,只需在字符串前添加不带引号的字符“r”即可
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
我在尝试打印文本时偶然发现了这个问题,我可以将粘贴复制到Latex文档中。我扩展并使用命名替换字段: 假设您想要打印出多个变量的乘积,其索引如下 ,在Latex中是
$A{0042}*A{3141}*A{2718}*A{0042}$
以下代码使用命名字段执行此任务,以便对许多索引保持可读性:
# to print '{I am inside braces}'
print(r'{I am inside braces}')
我最近遇到了这个问题,因为我想将字符串注入到预先格式化的JSON中。 我的解决方案是创建一个助手方法,如下所示:
idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))
from jinja2 import Template
foo = Template('''
#include <stdio.h>
void main() {
printf("hello universe number {{number}}");
}
''')
for i in range(2):
print(foo.render(number=i))
如果性能不是问题,则完成作业。如果只想打印一个大括号(例如
{
),则可以使用{
,如果需要,可以稍后在字符串中添加更多大括号。
例如:
formatted = preformat("""
{
"foo": "{{bar}}"
}""").format(bar="gas")
当您尝试插入代码字符串时,我建议使用Python的全功能模板引擎,即:
>>> 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'
来自jinja2导入模板的
foo=模板(“”)
#包括
void main(){
printf(“hello universe number{{{number}”);
}
''')
对于范围(2)中的i:
打印(foo.render(number=i))
因此,您不会被强制复制花括号,因为所有其他答案都建议使用转义序列来转义f字符串中的花括号。例如:print(f'{a={1}')我迟到了,真是可笑。我成功地将括号放入替换元素中,如下所示:
idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))
from jinja2 import Template
foo = Template('''
#include <stdio.h>
void main() {
printf("hello universe number {{number}}");
}
''')
for i in range(2):
print(foo.render(number=i))
哪张照片
print('{0} {1}'.format('{hello}', '{world}'))
严格地说,这不是OP所要求的,因为他/她想要格式字符串中的大括号,但这可能会对某人有所帮助。您可以使用“引号墙”将格式字符串部分与常规字符串部分分开
发件人:
到
一个更清楚的例子是
print("{Hello}"f" {42}")
NameError: name 'word' is not defined
输出:
string = 10
print(f"{string} {word}")
string = 10
print(f"{string}"" {word}")
现在,添加报价墙,如下所示:
输出:
string = 10
print(f"{string} {word}")
string = 10
print(f"{string}"" {word}")
如果在可以格式化的f字符串模板中需要大括号,则需要输出一个字符串,该字符串包含f字符串的一组大括号中的两个大括号:
css_template=f“{{tag}{{{{}边距:0;填充:0;{}”
for_p=css_template.format(tag=“p”)
#'p{margin:0;padding:0;}'
或者只是参数化括号本身?可能非常冗长
10 {word}
我使用了双{{}来防止fstring值注入 例如,下面是我的Postgres UPDATE语句,用于更新整数数组列,该列采用{}表达式来捕获数组,即: 端口=“{100200300}” 用它的弦
x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}')
print(x)
# {42}
实际的查询语句将是
ports = [1,2,3]
query = f"""
UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""
这是一个有效的postgres语句所以如果你想打印“{42}”,你应该使用
“{{{0}}}.format(42)
!如果你想要一个大括号呢?“{something{value}.format(42)
不起作用。{.format()和“}.format()打印一个大括号。在你的例子中,打印“{something{{0}.format(42)”将打印“{something{}42”。{0}
是什么意思?@Imray:{0}
引用.format()
的第一个参数。只要