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

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

    Try this:

    x = "{{ Hello }} {0}"

    0 讨论(0)
  • 2020-11-21 05:57

    If you need to keep two curly braces in the string, you need 5 curly braces on each side of the variable.

    >>> myvar = 'test'
    >>> "{{{{{0}}}}}".format(myvar)
    '{{test}}'
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-11-21 06:02

    If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

    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}'
    

    Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).

    0 讨论(0)
提交回复
热议问题