首页 > 解决方案 > 如何对输入进行切片并将其放在不同的行中(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 

标签: pythonjupyter-notebook

解决方案


如果你的问题真的是我想象的那样,你可以这样做:

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]

推荐阅读