How can I print literal curly-brace characters in python string and also use .format on it?

前端 未结 16 1626
面向向阳花
面向向阳花 2020-11-21 05:31
x = \" \\{ Hello \\} {0} \"
print(x.format(42))

gives me : Key Error: Hello\\\\

I want to print the output: {Hello} 42

16条回答
  •  醉酒成梦
    2020-11-21 05:39

    Python 3.6+ (2017)

    In the recent versions of Python one would use f-strings (see also PEP498).

    With f-strings one should use double {{ or }}

    n = 42  
    print(f" {{Hello}} {n} ")
    

    produces the desired

     {Hello} 42
    

    If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:

    hello = "HELLO"
    print(f"{{{hello.lower()}}}")
    

    produces

    {hello}
    

提交回复
热议问题