如何在字符串中打印文字大括号字符并在其上使用.format? [英] How can I print literal curly-brace characters in a string and also use .format on it?

查看:69
本文介绍了如何在字符串中打印文字大括号字符并在其上使用.format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x = " \{ Hello \} {0} "
print(x.format(42))

给我:关键错误:Hello \\

我要打印输出: {Hello} 42

推荐答案

您需要将 {{{}} 翻倍:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

这是 Python文档中有关格式字符串语法的相关部分:

格式字符串包含用花括号 {} 包围的替换字段".花括号中不包含的所有内容均视为文字文本,该文本原样复制到输出中.如果您需要在文字文本中包含大括号字符,可以通过以下操作将其转义: {{{ and }} .

Format strings contain "replacement fields" surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

这篇关于如何在字符串中打印文字大括号字符并在其上使用.format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆