Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting string width with f-strings [duplicate]

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         |
like image 509
Ray Salemi Avatar asked Jul 25 '26 22:07

Ray Salemi


2 Answers

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         |
like image 181
Brian Avatar answered Jul 28 '26 12:07

Brian


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

like image 40
pecey Avatar answered Jul 28 '26 12:07

pecey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!