How do I read multiple lines of raw input in Pytho

2019-01-01 00:51发布

I want to create a Python program which takes in multiple lines of user input. For example:

This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.

How can I take in multiple lines of raw input?

5条回答
还给你的自由
2楼-- · 2019-01-01 01:33
sentinel = '' # ends when this string is seen
for line in iter(raw_input, sentinel):
    pass # do things here

To get every line as a string you can do:

'\n'.join(iter(raw_input, sentinel))

Python 3:

'\n'.join(iter(input, sentinel))
查看更多
只若初见
3楼-- · 2019-01-01 01:35

Keep reading lines until the user enters an empty line (or change stopword to something else)

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s\n" % line
print text
查看更多
无与为乐者.
4楼-- · 2019-01-01 01:41

Alternatively,You can try sys.stdin.read()

import sys
s = sys.stdin.read()
print(s)
查看更多
高级女魔头
5楼-- · 2019-01-01 01:41

Try this

import sys

lines = sys.stdin.read().splitlines()

print(lines)

INPUT:

1

2

3

4

OUTPUT: ['1', '2', '3', '4']

查看更多
临风纵饮
6楼-- · 2019-01-01 01:49

Just extending this answer https://stackoverflow.com/a/11664652/4476612 instead of any stop word you can just check whether a line is there or not

content = []
while True:
    line = raw_input()
    if line:
        content.append(line)
    else:
        break

you will get the lines in a list and then join with \n to get in your format.

print '\n'.join(content)
查看更多
登录 后发表回答