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}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With