如何使用 .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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是新的样式:
但我认为转义有点难以阅读,所以我更喜欢切换回旧的样式以避免转义:
Here is the new style:
But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping: