【发布时间】:2020-02-16 04:53:18
【问题描述】:
我想输入变量名称并将它们转换为实际变量,类似于您可以使用打印语句执行的操作。这可能吗?
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
解决方案: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
【问题讨论】:
-
@Thierry 这不是正确的骗子
-
@MadPhysicist 我阅读的问题越多,我就越不确定 OP 想要什么,实际上......你有更好的副本吗?
-
@Thierry。 OP 希望将用户输入格式化为 f 字符串。他们忘记在输入之前在前两个作业的右侧加上引号,但我认为这并不重要。
标签: python python-3.x