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

前端 未结 16 1585
面向向阳花
面向向阳花 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:38

    Although not any better, just for the reference, you can also do this:

    >>> x = '{}Hello{} {}'
    >>> print x.format('{','}',42)
    {Hello} 42
    

    It can be useful for example when someone wants to print {argument}. It is maybe more readable than '{{{}}}'.format('argument')

    Note that you omit argument positions (e.g. {} instead of {0}) after Python 2.7

提交回复
热议问题