如何使用 .format() 打印字符串,并在替换的字符串周围打印文字大括号

发布于 2024-12-18 15:53:46 字数 817 浏览 5 评论 0原文

可能的重复:
如何打印python 字符串中的文字“{}”字符并在其上使用 .format?

基本上,我想使用 .format(),如下所示:

my_string = '{{0}:{1}}'.format('hello', 'bonjour')

并使其匹配:

my_string = '{hello:bonjour}' #this is a string with literal curly brackets

但是,第一段代码给了我一个错误。

大括号很重要,因为我正在使用 Python 通过基于文本的命令与软件进行通信。我无法控制 fo 软件需要什么样的格式,因此我自己整理出所有格式至关重要。它在字符串周围使用大括号来确保字符串中的空格被解释为单个字符串,而不是多个参数 - 例如,就像通常在文件路径中使用引号一样。

我目前正在使用旧的方法:

my_string = '{%s:%s}' % ('hello', 'bonjour')

这当然有效,但是 .format() 似乎更容易阅读,当我在一个字符串中发送包含五个或更多变量的命令时,可读性就成为一个重要问题。

谢谢!

Possible Duplicate:
How can I print a literal “{}” characters in python string and also use .format on it?

Basically, I want to use .format(), like this:

my_string = '{{0}:{1}}'.format('hello', 'bonjour')

And have it match:

my_string = '{hello:bonjour}' #this is a string with literal curly brackets

However, the first piece of code gives me an error.

The curly brackets are important, because I'm using Python to communicate with a piece of software via text-based commands. I have no control over what kind of formatting the fosoftware expects, so it's crucial that I sort out all the formatting on my end. It uses curly brackets around strings to ensure that spaces in the strings are interpreted as single strings, rather than multiple arguments — much like you normally do with quotation marks in file paths, for example.

I'm currently using the older method:

my_string = '{%s:%s}' % ('hello', 'bonjour')

Which certainly works, but .format() seems easier to read, and when I'm sending commands with five or more variables all in one string, then readability becomes a significant issue.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

○愚か者の日 2024-12-25 15:53:46

这是新的样式:

>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'

但我认为转义有点难以阅读,所以我更喜欢切换回旧的样式以避免转义:

>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'

Here is the new style:

>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'

But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:

>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文