在一行中输入多个输入时无法输入字符串值Python

问题描述

使用以下代码

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)

如何在将输入保持在一行中的同时解决此问题?

解决方法

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

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 错误时,请确保左侧的变量数与右侧的值数相匹配。

,

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

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 + "!!")