如何在Python中将用户输入格式化为fstring?

2024-04-26 10:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想输入变量名并将它们转换为实际变量,类似于print语句。有可能吗?你知道吗

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

代码:

fruit=apples
colour=red

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

所需输入:

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

期望输出:

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)

输入:I love {fruit} and the colour {colour}

输出:I love apples and the colour red


Tags: andthemessageinputyourstringwithred
1条回答
网友
1楼 · 发布于 2024-04-26 10:45:00
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

相关问题 更多 >