1

I would like to input variables names and have them converted to actual variables, similar to what you can do with print statements. Is this possibe?

print(f'I love {fruit} and the colour {colour}')

Code:

fruit=apples
colour=red

message=input('Enter your message: ')
print(message)

Desired input:

Enter your message: I love {fruit} and the colour {colour}

Desired Output:

I love apples and the colour red

Solution: How can i use f-string with a variable, not with a string literal?

variables = {
    'fruit': 'apples',
    'colour': 'red'
}

message=input('Enter your message: ').format(**variables)
print(message)

Input: I love {fruit} and the colour {colour}

Output: I love apples and the colour red

1 Answers1

1
fruit = "apples"
colour = "red"

message = input('Enter your message: ')
words = [i for i in message.split()]
variables = [i[1:-1] for i in words if i[0] == '{' and i[-1] == '}']
for i in variables:
    if i == 'fruit':
        words[words.index('{fruit}')] = fruit
    if i == "colour":
        words[words.index('{colour}')] = colour

print(' '.join(words))

Input

Enter your message: I love {fruit} and the colour {colour}

Output

I love apples and the colour red
codrelphi
  • 1,075
  • 1
  • 7
  • 13