cli*_*ait -2 python escaping string-formatting python-2.x python-2.7
有关的:
使用花括号 ( {•••}
) 表示要格式化的字符串部分。如果您想使用文字花括号字符,以便它们被 忽略.format()
,您可以使用双花括号 ( {{•••}}
)。MCVE:
string = "{format} {{This part won't be formatted. The final string will have literal curly braces here.}}"
print string.format(format='string')
Run Code Online (Sandbox Code Playgroud)
如果您有.format()
s链,则每次使用.format()
. 最后一个被 4 个大括号包围,并在最终输出中以文字花括号结束。MCVE:
string = "{format1} {{format2}} {{{{3rd one won't be formatted. The final string will have literal curly braces here.}}}}"
print string.format(format1='string1').format(format2='string2')
Run Code Online (Sandbox Code Playgroud)
也可以将另一个格式字符串格式化为格式字符串。最后一个被 4 个大括号包围,并在最终输出中以文字花括号结束。MCVE:
string = "{format1} {{{{3rd one won't be formatted. The final string will have literal curly braces here.}}}}"
print string.format(format1='{format2}').format(format2='string')
Run Code Online (Sandbox Code Playgroud)
当您.format()
根据运行时确定的条件使用s链时,就会出现问题。如果您希望将一组花括号转义为文字字符,您使用多少个?MCVE:
string = "{} {{{{{{Here I don't know exactly how many curly braces to use because this string is formatted differently due to conditions that I have no control over.}}}}}}"
if fooCondition:
string = string.format('{} bar')
if barCondition:
string = string.format('{} baz')
if bazCondition:
string = string.format('{} buzz')
string = string.format('foo')
print string
Run Code Online (Sandbox Code Playgroud)
字符串的第一部分有 4 个可能的输出:
foo
foo bar
foo baz bar
foo buzz baz bar
字符串的第二部分以不同数量的花括号结束,具体取决于条件的数量True
。我希望第二部分的花括号永久转义,就像每次.format()
调用时都不要“脱落一层” 。我可以解决这样的问题,MCVE:
string = "{} {{DRY - Don't repeat yourself!}}"
if fooCondition:
string = string.format('{} bar').replace("{DRY - Don't repeat yourself!}", "{{DRY - Don't repeat yourself!}}")
if barCondition:
string = string.format('{} baz').replace("{DRY - Don't repeat yourself!}", "{{DRY - Don't repeat yourself!}}")
if bazCondition:
string = string.format('{} buzz').replace("{DRY - Don't repeat yourself!}", "{{DRY - Don't repeat yourself!}}")
string = string.format('foo')
print string
Run Code Online (Sandbox Code Playgroud)
MCVE 不是我真正的代码。我的真实代码在 Google App Engine 网络服务器上运行。它超级长而且复杂。我正在处理字符串中的 HTML、CSS 和 JavaScript。我想在.format()
不弄乱 CSS 和 JS 的花括号的情况下将内容插入到 HTML 中。我当前的实现是不可扩展的并且非常容易出错。我必须管理最多 5 个连续的花括号(像这样:){{{{{•••}}}}}
才能穿过.format()
链条而不受影响。我需要定期将花括号重新插入未格式化固定次数的字符串中。修复此意大利面代码的优雅方法是什么?
如何永久转义 Python 格式字符串中的花括号?
简单而明显的解决方案是,不要应用于.format()
您无法完全控制的字符串。相反,也许做
result = thestring.replace('{postURL}', url).replace('{postTitle}', title)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4142 次 |
最近记录: |