Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable inside python format specifier [duplicate]

Tags:

python

format

I am wondering whether I can add a variable inside the f string to specify the width of item to be printed. For example:

print("{:>5}".format("cat"))

In the example how can I replace 5 with a variable that can change at runtime.

like image 862
the__hat_guy Avatar asked May 19 '26 08:05

the__hat_guy


1 Answers

inside the f string

Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:

animal = 'cat'
pad = 5

print(f"{animal:>{pad}}")

Otherwise, if you just want a format string without the f-string, then @JohnnyMopp's comment (+1) shows the correct syntax.

like image 73
cdlane Avatar answered May 20 '26 21:05

cdlane



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!