Sch*_*tti 1320 python string format string-formatting curly-braces
x = " \{ Hello \} {0} "
print x.format(42)
Run Code Online (Sandbox Code Playgroud)
给我 : Key Error: Hello\\
我想打印输出: {Hello} 42
Gre*_*ill 1802
你需要加倍{{
和}}
:
>>> x = " {{ Hello }} {0} "
>>> print x.format(42)
' { Hello } 42 '
Run Code Online (Sandbox Code Playgroud)
格式字符串包含由大括号括起的"替换字段"
{}
.大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中.如果你需要在文字文本中包含一个大括号字符,可以通过加倍来转义它:{{
和}}
.
Nic*_*ens 86
{
您想要使用字符或来格式化字符串}
你只需要将它们加倍即可。
格式{
为f'{{'
和}
与f'}}'
所以 :
name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
Run Code Online (Sandbox Code Playgroud)
输出 :
你好鲍勃!我想打印 } 和 { 或 { }
或者对于确切的示例:
number = 42
print(f'{{Hello}} {number}')
Run Code Online (Sandbox Code Playgroud)
将打印:
{你好} 42
最后 :
name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
Run Code Online (Sandbox Code Playgroud)
{你好} {42} 42 {鲍勃} 鲍勃
Kam*_*iel 65
你通过加倍括号来逃避它.
例如:
x = "{{ Hello }} {0}"
print x.format(42)
Run Code Online (Sandbox Code Playgroud)
twa*_*lig 39
OP写了这样的评论:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
Run Code Online (Sandbox Code Playgroud)
在处理JSON时出现"逃避大括号"问题是很常见的.
我建议这样做:
'{{"all": false, "selected": "{}"}}'.format(data)
Run Code Online (Sandbox Code Playgroud)
它比替代品更清洁,它是:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
Run Code Online (Sandbox Code Playgroud)
'{"all": false, "selected": "{}"}'.format(data)
当JSON字符串比示例更复杂时,使用库肯定是更可取的.
div*_*nex 34
Python 3.6+(2017)
在最近的Python版本中,人们会使用f-strings(另请参阅PEP498).
使用f-strings,应该使用double {{
或}}
n = 42
print(f" {{Hello}} {n} ")
Run Code Online (Sandbox Code Playgroud)
产生所需的
{Hello} 42
Run Code Online (Sandbox Code Playgroud)
如果您需要在括号中解析表达式而不是使用文字文本,则需要三组括号:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
Run Code Online (Sandbox Code Playgroud)
产生
{hello}
Run Code Online (Sandbox Code Playgroud)
DNR*_*DNR 24
试着这样做:
x = " {{ Hello }} {0} "
print x.format(42)
Run Code Online (Sandbox Code Playgroud)
Geo*_*lis 14
虽然没有更好,仅供参考,您也可以这样做:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
Run Code Online (Sandbox Code Playgroud)
例如,当有人想要打印时,它可能很有用{argument}
.它可能比可读性更强'{{{}}}'.format('argument')
请注意,在Python 2.7之后省略了参数位置(例如,{}
而不是{0}
)
ccp*_*zza 14
您可以通过仅对要应用 f 魔法的字符串部分使用 f 字符串来避免必须使用双大括号,并对所有文字且可能包含 \'unsafe\ 的内容使用常规(哑)字符串' 特殊字符。让 python只需将多个字符串堆叠在一起即可完成字符串连接。
\nnumber = 42\nprint("{The answer is} " \nf"{number}" \n" {thanks for all the fish}")\n\n### OUTPUT:\n{The answer is} 42 {thanks for all the fish}\n
Run Code Online (Sandbox Code Playgroud)\n\n\n注意:字符串之间不需要换行。我添加它们只是为了便于阅读。您也可以将上面的代码写成如下所示:
\n\xe2\x9a\xa0\xef\xb8\x8f 警告:这可能会伤害您的眼睛或让您头晕!
\nRun Code Online (Sandbox Code Playgroud)\nprint("{The answer is} "f"{number}"" {thanks for all the fish}")\n
def*_*ant 12
key = "FOOBAR"
print(f"hello {{{key}}}")
Run Code Online (Sandbox Code Playgroud)
输出
hello {FOOBAR}
Run Code Online (Sandbox Code Playgroud)
如果有人想使用 fstring 在大括号内打印一些内容。
如果需要在字符串中保留两个花括号,则变量的每一侧都需要 5 个花括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
Run Code Online (Sandbox Code Playgroud)
如果你要做很多事情,最好定义一个实用函数,它可以让你使用任意的替代支撑,比如
def custom_format(string, brackets, *args, **kwargs):
if len(brackets) != 2:
raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
padded = string.replace('{', '{{').replace('}', '}}')
substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
formatted = substituted.format(*args, **kwargs)
return formatted
>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'
Run Code Online (Sandbox Code Playgroud)
请注意,这将使用括号为长度为2的字符串或两个字符串的可迭代(对于多字符分隔符).
小智 5
我最近遇到了这个问题,因为我想将字符串注入到预先格式化的 JSON 中。我的解决方案是创建一个辅助方法,如下所示:
def preformat(msg):
""" allow {{key}} to be used for formatting in text
that already uses curly braces. First switch this into
something else, replace curlies with double curlies, and then
switch back to regular braces
"""
msg = msg.replace('{{', '<<<').replace('}}', '>>>')
msg = msg.replace('{', '{{').replace('}', '}}')
msg = msg.replace('<<<', '{').replace('>>>', '}')
return msg
Run Code Online (Sandbox Code Playgroud)
然后你可以做类似的事情:
formatted = preformat("""
{
"foo": "{{bar}}"
}""").format(bar="gas")
Run Code Online (Sandbox Code Playgroud)
如果性能不是问题,就可以完成工作。
归档时间: |
|
查看次数: |
369783 次 |
最近记录: |