简体   繁体   English

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

[英]Unable to input string values when taking multiple input in one line (Python)

Using the code below:使用下面的代码:

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

I can input single variable (eg - a/b/c or 1/2/3) and the program works fine but it we input string values or words(eg- Canada,New_york), I get the following error - too many values to unpack (expected 2)我可以输入单个变量(例如 - a/b/c 或 1/2/3)并且程序运行良好,但我们输入字符串值或单词(例如 - Canada,New_york),我收到以下错误 -值太多解包(预期 2)

How can I resolve this while keeping input in one line?如何在将输入保持在一行的同时解决此问题?

You need to replace the + with a , since the + is going to concatenate your inputs into one string.您需要将+替换为,因为+会将您的输入连接成一个字符串。

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

Whenever you get the too many values to unpack Error, make sure that the number of variables on the left side matches the number of values on the right side.每当你得到too many values to unpack错误时,请确保左侧的变量数量与右侧的值的数量相匹配。

Use the split function,it helps in getting a multiple inputs from user.使用拆分 function,它有助于从用户那里获得多个输入。 It breaks the given input by the specified separator.它通过指定的分隔符打破给定的输入。 If a separator is not provided then any white space is a separator.如果未提供分隔符,则任何空格都是分隔符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM