Formatting string width with f-strings

3.4k Views Asked by At

I'm trying to create headers of a given width and would like to use

>>> print(f'{"string":15<}|')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: Unknown format code '<' for object of type 'str'

Are we meant to cobble together headers like this or am I missing something about f strings?

print('string'+" "*(15-len('string'))+"|")
string         |
2

There are 2 best solutions below

3
On BEST ANSWER

Per the Python Format Specification Mini-Language, alignment specifiers (e.g. <) must precede the width specifier (e.g. 15). With this criteria in mind, the correct formulation for your format string is {:<15}. However, left-alignment is inferred by default for strings, so you can write this simply as {:15}.

>>> print(f'{"string":<15}|')
string         |
>>> print(f'{"string":15}|')
string         |
0
On

I think what you are looking for is simply print(f'{"string":15}|')