how to get around "Single '}' encountered in format string" when using .format and formatting in printing
Question:
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.
ValueError: Single '}' encountered in format string
Here’s the line:
print("{0}:<15}{1}:<15}{2}:<8}".format("1", "2", "3"))
Required output is something along the lines of:
1 2 3
I’ve tried duplicating the { } as advised here but received no luck.
I am probably missing something incredibly obvious however after staring at it for ages, I cannot see it. After all, what’s the harm in asking?
Thanks
Answers:
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"))
Use }}
:
>>> "{0}:<15}}{1}:<15}}{2}:<8}}".format("1", "2", "3")
'1:<15}2:<15}3:<8}'
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}
You can also use Variables to do that. lenmax = the max number of space needed, and op = the var i want to format with (both vars need to be set first)
print(('{:>' + str(lenmax) + '}').format(op), end='tt')
Things to remember:
- Parenthesis can be used.
- you can’t concat ints so the var on the string must be transformed.
- the end statement gives you Tab so you don’t have linejumps
hope works for someone.
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.
ValueError: Single '}' encountered in format string
Here’s the line:
print("{0}:<15}{1}:<15}{2}:<8}".format("1", "2", "3"))
Required output is something along the lines of:
1 2 3
I’ve tried duplicating the { } as advised here but received no luck.
I am probably missing something incredibly obvious however after staring at it for ages, I cannot see it. After all, what’s the harm in asking?
Thanks
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"))
Use }}
:
>>> "{0}:<15}}{1}:<15}}{2}:<8}}".format("1", "2", "3")
'1:<15}2:<15}3:<8}'
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}
You can also use Variables to do that. lenmax = the max number of space needed, and op = the var i want to format with (both vars need to be set first)
print(('{:>' + str(lenmax) + '}').format(op), end='tt')
Things to remember:
- Parenthesis can be used.
- you can’t concat ints so the var on the string must be transformed.
- the end statement gives you Tab so you don’t have linejumps
hope works for someone.