【问题标题】:Unable to input string values when taking multiple input in one line (Python)在一行中进行多个输入时无法输入字符串值(Python)
【发布时间】:2021-05-29 06:38:52
【问题描述】:

使用以下代码:

print("Welcome to band name generator!!")
city,pet = input("What is the name of the city you grew up in?\t") + input ("\nWhat is the name of your first pet?\t")
print("\n\t Your band name can be " + city + " "+ pet + "!!")

我可以输入单个变量(例如 - a/b/c 或 1/2/3)并且程序运行良好,但是我们输入字符串值或单词(例如 - Canada,New_york),我收到以下错误 - 要解压的值太多(预计 2 个)

如何在一行输入的同时解决这个问题?

【问题讨论】:

  • 您正在将 Canada,New_york 分配给一个单值城市。因此错误

标签: python python-3.x multiple-input


【解决方案1】:

您需要将+ 替换为,,因为+ 会将您的输入连接成一个字符串。

city, pet = input("What is the name of the city you grew up in?\t"), input ("\nWhat is the name of your first pet?\t")

每当您收到too many values to unpack 错误时,请确保左侧的变量数与右侧的值数匹配。

【讨论】:

    【解决方案2】:

    使用拆分功能,它有助于从用户那里获得多个输入。它通过指定的分隔符打破给定的输入。如果没有提供分隔符,则任何空格都是分隔符。

    print("Welcome to band name generator!!")
    city,pet = input("Enter the city and pet name  ").split()
    print("\n\t Your band name can be " + city + " "+ pet + "!!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2014-08-19
      相关资源
      最近更新 更多