微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在一行中输入多个输入时无法输入字符串值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 + "!!")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。