如何从用户获取多行输入 [英] How to get multiline input from user

查看:93
本文介绍了如何从用户获取多行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,获取多个行输入并逐行处理它.为什么在Python 3中没有像raw_input这样的函数?

I want to write a program that gets multiple line input and work with it line by line. Why there is no function like raw_input in Python 3?

input不允许用户放置换行符( Enter ),仅打印第一行.

input does not allow user to put lines separated by newline (Enter), it prints back only the first line.

它可以存储在变量中,甚至可以读取到列表中吗?

Can it be stored in variable or even read it to a list?

推荐答案

在Python 3.x中,Python 2.x的raw_input()已由input()函数替换.但是,在两种情况下,您都无法输入多行字符串,为此,您需要从用户行中逐行获取输入,然后使用\n .join()对其进行输入,或者也可以采用多种行并将其连接起来+运算符,以\n

In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n

要从用户那里获得多行输入,您可以像这样:

To get multi-line input from the user you can go like:

no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
    lines+=input()+"\n"

print(lines)

lines = []
while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break
text = '\n'.join(lines)

这篇关于如何从用户获取多行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆