'How do I format my numbers correctly for an addition equation

Ok, so I am trying to make a program that implements the main() function to make a random addition equation when it is called, using numbers up to 3 digits. This is what I have so far:

def main():
    
    import random

# Generating random 3 digit number
    num1 = random.randint(1,1000)
    num2 = random.randint(1,1000)

#Displying the three digit numbers
    print(" ",num1)
    print("+",num2)


    answer = num1 + num2
    user_answer = int(input("Enter sum of numbers: "))
    if user_answer == answer:
        print("Correct answer - Good Work!")
    else:
        print("Incorrect... The Correct answer is:", + answer)
main()

The thing I am having issues with is the formatting for the generated numbers. Since they are random, you could generate something like 375 + 67, which would make the output like this:

  375
+ 67
Enter sum of numbers: 

The immediate issue here is that it isn't aligned with the right place, so it is difficult to do addition. I want it to be aligned in the correct place like this:

  375
+  67
Enter sum of numbers: 

Is there an argument in the format function that lets me align it correctly using a blank space like ' '?



Solution 1:[1]

Try right-aligning the outputs using string formatting. The general syntax would be f"{yourValue:>width}".

print(f"{num1:>2}")
print(f"+ {num2:>2}")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayosensei