【问题标题】:Why the code is stopping after first f-string?为什么代码在第一个 f 字符串之后停止?
【发布时间】:2020-12-22 21:25:07
【问题描述】:

我正在尝试根据提供的字典打印出两条语句,但出现问题并且代码在第一个 f 字符串之后停止(第二个不显示)。我想它可能是类似的东西,但无法弄清楚错误:

data = [
{
    'name': 'Instagram',
    'follower_count': 346,
    'description': 'Social media platform',
    'country': 'United States'
},
{
    'name': 'Cristiano Ronaldo',
    'follower_count': 215,
    'description': 'Footballer',
    'country': 'Portugal'
}]

a = input(f"Compare A: {data[1]['name']}, {data[1]['description']}, from {data[1]['country']}")
b = input(f"Compare B: {data[0]['name']}, {data[0]['description']}, from {data[0]['country']}")

【问题讨论】:

  • input input 停止并要求用户输入一些内容。尝试打印
  • 您正在调用input(),这会暂停程序,直到用户键入内容并按 Enter 键。如果您只想显示字符串,请使用print()
  • 谢谢!现在一切都清楚了)

标签: python f-string


【解决方案1】:

这个怎么样?

data = [
{
    'name': 'Instagram',
    'follower_count': 346,
    'description': 'Social media platform',
    'country': 'United States'
},
{
    'name': 'Cristiano Ronaldo',
    'follower_count': 215,
    'description': 'Footballer',
    'country': 'Portugal'
}]

a = print(f"Compare A: {data[1]['name']}, {data[1]['description']}, from {data[1]['country']}")
b = print(f"Compare B: {data[0]['name']}, {data[0]['description']}, from {data[0]['country']}")

结果如下:

Compare A: Cristiano Ronaldo, Footballer, from Portugal
Compare B: Instagram, Social media platform, from United States

【讨论】:

  • 将 a 和 b 分配给 print 的结果有什么意义,它什么都不返回?
【解决方案2】:

这是一个关于如何打印 a 和 b 的示例:

data = [
{
    'name': 'Instagram',
    'follower_count': 346,
    'description': 'Social media platform',
    'country': 'United States'
},
{
    'name': 'Cristiano Ronaldo',
    'follower_count': 215,
    'description': 'Footballer',
    'country': 'Portugal'
}]

print("比较 A: {" + data[1]['name'] + "}, {" + data[1]['description'] + "}, " + "from {" + data[ 1]['国家']"}") print("比较 B: {" + data[0]['name']+ "}, {" + data[0]['description'] + "}," + "from {" + data[0][ '国家'] + "}")

【讨论】:

  • 将 a 和 b 分配给 print 的结果有什么意义,它什么都不返回?
  • 大声笑你是对的。我只是想尽快输入答案。错过了那个地方!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多