3
aStr = input("Enter a string message: ")
fW = eval(input("Enter a positive integer: "))
print(f"Right aligned is <{aStr:>fW}>")

so, this is my code, I would like to align the spaces according to the user input. Whenever I try to use eval or int in fW, it shows this error.

Traceback (most recent call last):
  File "C:\Users\vmabr\Downloads\A1Q2.py", line 5, in <module>
    print(f"Right aligned is <{aStr:fW}>")
ValueError: Invalid format specifier

May I know what's the fix?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • try: `aStr = input("Enter a string message: ") fW = int(input("Enter a positive integer: ")) print(f"Right aligned is <{aStr.rjust(fW)}>")` – Byron Oct 17 '22 at 12:49
  • Before you learn anything else, you should unlearn that the `eval` function exists. `eval` is not safe to use, _especially_ on unsanitized user input as you have done. See https://stackoverflow.com/q/1832940/843953 – Pranav Hosangadi Oct 18 '22 at 05:39
  • Oh, I didn't know that. My professor was the one who recommended me to use eval so I just followed. Thank you very much for letting me know – completenewbie001 Oct 19 '22 at 12:23

1 Answers1

3

You were close. To implement a "parameterized" format-string, you need to wrap the parameter fW into additional curly braces:

aStr = input("Enter a string message: ")
fW = int(input("Enter a positive integer: "))
print(f"Right aligned is <{aStr:>{fW}}>")  # {fW} instead of fW

See PEP 498 -> format specifiers for further information.

Christian Karcher
  • 2,533
  • 1
  • 12
  • 17
  • Thank you so much! It works like magic! Curse these curly brackets . . . Oh and also thanks for the link, I will definitely check it out. – completenewbie001 Oct 19 '22 at 12:26