Py学习  »  Python

在Python中提示时,如何允许用户输入多行?当按下Enter或在输入中使用/n时,它不起作用

ninja6714 • 4 年前 • 440 次点击  

我想写一个程序,得到多行输入,并与它逐行工作。为什么没有 raw_input 在Python 3中?

input 进入 ),它只打印回第一行。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57180
 
440 次点击  
文章 [ 5 ]  |  最新文章 4 年前
Michael Dorner mohankumar.A
Reply   •   1 楼
Michael Dorner mohankumar.A    7 年前
no_of_lines = 5
lines = ""
for i in xrange(5):
    lines+=input()+"\n"
    a=raw_input("if u want to continue (Y/n)")
    ""
    if(a=='y'):
        continue
    else:
        break
    print lines
maggick
Reply   •   2 楼
maggick    8 年前

使用 input() 从用户获取输入行的内置函数。

你可以阅读 the help here .

您可以使用以下代码一次获取多行(以空行结束):

while input() != '':
    do_thing
RufusVS chepner
Reply   •   3 楼
RufusVS chepner    8 年前

input(prompt)

def input(prompt):
    print(prompt, end='', file=sys.stderr)
    return sys.stdin.readline()

你可以直接从 sys.stdin 如果你愿意的话。

lines = sys.stdin.readlines()

lines = [line for line in sys.stdin]

five_lines = list(itertools.islice(sys.stdin, 5))

Raj xiaket
Reply   •   4 楼
Raj xiaket    5 年前

raw_input 可以正确处理EOF,因此我们可以编写循环,读取直到收到用户的EOF(Ctrl-D):

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

巨蟒2

print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
    try:
        line = raw_input("")
    except EOFError:
        break
    contents.append(line)
AMGMNPLK ZdaR
Reply   •   5 楼
AMGMNPLK ZdaR    4 年前

在Python 3.x中 raw_input() Python 2.x的 input() 功能。但是,在这两种情况下,您都不能输入多行字符串,为此,您需要逐行从用户处获取输入,然后 .join() 他们使用 \n ,或者也可以采用不同的行并使用 + 运算符分隔为

要从用户处获取多行输入,可以执行以下操作:

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)