How to read multiple lines of raw input?
sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
pass # do things here
To get every line as a string you can do:
'\n'.join(iter(input, sentinel))
Python 2:
'\n'.join(iter(raw_input, sentinel))
How to get multiline input from the user
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)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
How to read more than one line in an input in Python?
If you wanna read 3 line of input. You can do like this.
inputs = [input() for i in range(3)]
inputs
variable will be a list
Python3 best way to read unknown multi line input
The EOFError
occurs when you call input()
, not when you test it, nor when you print it. So that means you should put input()
in a try
clause:
try:
line = input()
print(line)
except EOFError:
break
That being said, if input
reads from the standard input channel, you can use it as an iterable:
import sys
for line in sys.stdin:
print(line, end='')
Since every line
now ends with the new line character '\n'
, we can use end=''
in the print
function, to prevent print a new line twice (once from the string, once from the print
function).
I think the last version is more elegant, since it almost syntactically says that you iterate over the stdin
and processes the lines individually.
Related Topics
How to Select Last Row and Also How to Access Pyspark Dataframe by Index
How to Bold Text in Telepot Telegram Bot
Pyspark Regexp_Replace With List Elements Are Not Replacing the String
How to Sort a Single String Output in Ascii Descending Order Through a Function
Python - Split Array into Multiple Arrays
Python Creating Dictionary from Excel Data
Invalidargumenterror: Logits and Labels Must Have the Same First Dimension Seq2Seq Tensorflow
How to Fix the 403:Insufficient Authentication Scopes Error from Google Analytics User Deletion API
How to Completely Remove Python from a Windows Machine
Tensorflow - Valueerror: Failed to Convert a Numpy Array to a Tensor (Unsupported Object Type Float)
Python Pandas: Drop Rows of a Timeserie Based on Time Range
How to Print Float to N Decimal Places Including Trailing 0S
Get List of Files in a Sharepoint Directory Using Python
Deleting Rows from CSV Based on Cell Contents from Another Csv
How to Remove All Characters Before a Specific Character in Python
How to Stop Execution of Python Script in Visual Studio Code
How to Check Whether a Number Is Divisible by Another Number