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

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

    I stumbled upon this problem when trying to print text, which I can copy paste into a Latex document. I extend on this answer and make use of named replacement fields:

    Lets say you want to print out a product of mulitple variables with indices such as , which in Latex would be $A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$ The following code does the job with named fields so that for many indices it stays readable:

    idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
    print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))
    

提交回复
热议问题