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.
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.
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.
Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust()
:
a = 5
print("cat".rjust(a))
Output:
cat