python - 如何对输入进行切片并将其放在不同的行中(python)
问题描述
我有不同问题的输入,因此用户应该能够在一行中输入所有答案并获得输出
Q1 c
Q2 b
Q3 d
但是当我对当前输入进行切片时,我得到c b d
了(我需要它们在不同的行上)
代码:
input_str = "What are your answers for Q1 to Q10? (leave a space between each answer) "
qns = input(input_str)
print(qns)
questions = qns.split(" ")
Q1 = (questions[0])
Q2 = (questions[1])
Q3 = (questions[2])
Q4 = (questions[3])
输出:
What are your answers for Q1 to Q10? (leave a space between each answer) a b c d e
a b c d
解决方案
如果你的问题真的是我想象的那样,你可以这样做:
input_str = "What are your answers for Q1 to Q10? (leave a space between each answer) "
answers_string = input(input_str)
answers = answers_string.split()
for num, answer in enumerate(answers, start=1):
print(f'Q{num} {answer}')
样品运行:
What are your answers for Q1 to Q10? (leave a space between each answer) a b d c
Q1 a
Q2 b
Q3 d
Q4 c
不带参数使用split
会使它在任何类型的空格上拆分。第二个参数enumerate
是起始值。
如果你想接受不超过 10 个答案,你可以分割答案列表:
answers = answers_string.split()[:10]
推荐阅读
- maven - (误报)使用 gitlab-ci 运行 docker-compose:构建作业失败但管道成功
- java - JTable排序器对整数和双精度排序不正确
- excel - VBA复选框取消选中事件和多个范围加载到列表框
- python - 在 Tkinter 文件对话框中选择文件后出现“不本地化”警告
- types - 尝试将常规浮点值添加到具有浮点的类型
. F# - mongodb - 单个成员副本集可以吗?
- python - 如何在Python中提取括号之间的值
- angularjs - 如何动态绑定自定义 AngularJS 模态?
- c# - 如何:MSAL 和 ASP.NET MVC Web 应用程序配置?
- powershell - 管道到格式表时,自定义注释中的原始数据与 power-shell 中的函数