Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify width of literal character strings in a Python f-string?

In Python 3.6+, one can print integer literals in columns of a specified width with an f-string as in

print(f"{1:10}{2:10}{3:10}")

How can I do something similar with string literals? i.e. Instead of printing 1, 2, and 3 in 10-character columns, how would I print "One", "Two", and "Three" in 10-character columns?

Can it be done using an f-string with a single line of code, or must I code it as follows?

a = "One"
b = "Two"
c = "Three"
print(f"{a:10}{b:10}{c:10}"
like image 882
Kevin Kleinfelter Avatar asked Sep 04 '25 16:09

Kevin Kleinfelter


1 Answers

You can do a one-liner with strings using the following format:

print(f"{'One':>10}")
#        One

See the docs here. Note the relevant section:

> Forces the field to be right-aligned within the available space (this is the default for numbers).

(Emphasis added)

This is why you don't need the > when formatting numbers.

like image 198
jdaz Avatar answered Sep 07 '25 19:09

jdaz