Search code examples
pythonvariablesformattingprompt

How do I format text using a variable?


Basically, I want to be able to ask a question like "What colour do you want?" and then make it so that based on the answer it will set a variable and be usable in formatting.

So something like this:

print("\033[1;35m\033[1;4m What colour would you like the printed text to be?")
print("\033[1;0m\033[1;1m    1. Red")
print("    2. Green")
print("    3. Blue")
ans1 = input()
ans1 = float(ans1)

if ans1 == 1:
    colour = 31
    print("\033[1;(colour)m This text is red")

elif ans1 == 2:
    colour = 32
    print("\033[1;(colour)m This text is green")

elif ans1 == 3:
    colour = 35
    print("\033[1;(colour)m This text is blue")

and then the text would be the right colour. Is this possible and if so how could I go about doing it?


Solution

  • print("\033[1;35m\033[1;4m What colour would you like the printed text to be?")
    print("\033[1;0m\033[1;1m    1. Red")
    print("    2. Green")
    print("    3. Blue")
    ans1 = input()
    ans1 = float(ans1)
    
    if ans1 == 1:
        colour = 31
        print(f"\033[1;{colour}m This text is red")
    
    elif ans1 == 2:
        colour = 32
        print(f"\033[1;{colour}m This text is green")
    
    elif ans1 == 3:
        colour = 35
        print(f"\033[1;{colour}m This text is blue")
    
    
    

    A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.