how to get around “Single '}' encountered in format string” when using .format and formatting in printing

后端 未结 3 616
醉梦人生
醉梦人生 2021-02-18 13:47

I am currently trying to print a tabulated format (using left alignment and padding) for headings in a table however I keep getting the following error.

ValueErr         


        
相关标签:
3条回答
  • 2021-02-18 13:55

    Use }}:

    >>> "{0}:<15}}{1}:<15}}{2}:<8}}".format("1", "2", "3")
    '1:<15}2:<15}3:<8}'
    
    0 讨论(0)
  • 2021-02-18 13:57

    The { and } characters need to be escaped where they're not part of the formatting template.

    Try: print("{0}:<15}}{1}:<15}}{2}:<8}}".format("1", "2", "3"))

    Outputs: 1:<15}2:<15}3:<8}

    0 讨论(0)
  • 2021-02-18 14:00

    Works:

    >>> print("{0}:<15}}{1}:<15}}{2}:<8}}".format("1", "2", "3"))
    1:<15}2:<15}3:<8}
    

    Edit: Now I understand you. Do this:

    print("{0:<15}{1:<15}{2:<8}".format("1", "2", "3"))
    

    Details: http://www.python.org/dev/peps/pep-3101/

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