2

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         |
Ray Salemi
  • 5,247
  • 4
  • 30
  • 63

2 Answers2

8

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         |
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
2

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

pecey
  • 651
  • 5
  • 13