3

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.

the__hat_guy
  • 133
  • 8

2 Answers2

1

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.

cdlane
  • 40,441
  • 5
  • 32
  • 81
0

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
Red
  • 26,798
  • 7
  • 36
  • 58