【问题标题】:How do you format user input as an f-string in Python? [duplicate]如何在 Python 中将用户输入格式化为 f 字符串? [复制]
【发布时间】: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


【解决方案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))

输入

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

输出

I love apples and the colour red

【讨论】:

  • 你可以让str.format为你做所有这些......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多