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?

3
  • try: aStr = input("Enter a string message: ") fW = int(input("Enter a positive integer: ")) print(f"Right aligned is <{aStr.rjust(fW)}>") Commented Oct 17, 2022 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 stackoverflow.com/q/1832940/843953 Commented Oct 18, 2022 at 5: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 Commented Oct 19, 2022 at 12:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.