【问题标题】:How can I print a string using .format(), and print literal curly brackets around my replaced string [duplicate]如何使用 .format() 打印字符串,并在替换的字符串周围打印文字大括号 [重复]
【发布时间】:2012-01-10 05:04:07
【问题描述】:

可能重复:
How can I print a literal “{}” characters in python string and also use .format on it?

基本上,我想使用.format(),像这样:

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

并让它匹配:

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

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

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

我目前正在使用旧方法:

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

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

谢谢!

【问题讨论】:

标签: python string formatting string-formatting curly-brackets


【解决方案1】:

这是新样式:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多