How do I format text using a variable?

Question:

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("33[1;35m33[1;4m What colour would you like the printed text to be?")
print("33[1;0m33[1;1m    1. Red")
print("    2. Green")
print("    3. Blue")
ans1 = input()
ans1 = float(ans1)

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

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

elif ans1 == 3:
    colour = 35
    print("33[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?

Asked By: Kian Murray

||

Answers:

Try this way too.

from termcolor import COLORS, colored

colour = input('Enter Color name: ').lower()

if colour in COLORS:
    print(colored(f"This is {colour} text.",colour))

else:
    print("THis color is invalid.")

YOur way.
Use f-string.

Try this.

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

if ans1 == 1:
    colour = 31
    print(f"33[1;{colour}m This text is red")

elif ans1 == 2:
    colour = 32
    print(f"33[1;{colour}m This text is green")

elif ans1 == 3:
    colour = 34 # not 35 for blue it is 34
    print(f"33[1;{colour}m This text is blue")

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

if ans1 == 1:
    colour = 31
    print(f"33[1;{colour}m This text is red")

elif ans1 == 2:
    colour = 32
    print(f"33[1;{colour}m This text is green")

elif ans1 == 3:
    colour = 35
    print(f"33[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.

Answered By: Vkyal