Skip to main content
 首页 » 编程设计

python之在 Python 中打印 {1}

2025年05月04日16zengkefu

我想在 Python 3.5 中得到一个看起来像 {1} 的打印输出,但我没有得到正确的 .format 语法。我试过:

print('{{}}'.format('1'))        # prints {} 
print('{{id}}'.format(id='1'))   # prints {id} 
print('{{0}}'.format('1'))       # prints {0} 
print('\{{}\}'.format(1))        # ValueError: Single '}' encountered in format string 

打印类似 {1} 的正确 print('{}'.format()) 语法是什么?

请您参考如下方法:

你可以这样做:

>>> print('{{{}}}'.format(1)) 
{1} 

最里面的 {} 用于插入 1。最外面的 {{ 和 }} 用于打印 { 和 } 但你需要其中两个来打印转义 { 和 }(因为它们通常用于指示位置)。