Python command Line - multiple Line Input

11,539

Solution 1

Upon reaching end of stream on input, raw_input will return an empty string. So if you really need to accumulate entire input (which you probably should be avoiding given SPOJ constraints), then do:

buffer = ''
while True:
    line = raw_input()
    if not line: break

    buffer += line

# process input

Solution 2

Since raw_input() is designed to read a single line, you may have trouble this way. A simple solution would be to put the input string in a text file and parse from there.

Assuming you have input.txt you can take values as

f = open(r'input.txt','rU')
for line in f:
  print line,

Solution 3

Using the best answer here, you will still have an EOF error that should be handled. So, I just added exception handling here

buffer = ''
while True:
    try:
         line = raw_input()
    except EOFError:
         break
    if not line: 
         break

    buffer += line

Solution 4

Since the end-of-line on Windows is marked as '\r\n' or '\n' on Unix system it is straight forward to replace those strings using

your_input.replace('\r\n', '')

Share:
11,539
Dreiven
Author by

Dreiven

Updated on June 16, 2022

Comments

  • Dreiven
    Dreiven almost 2 years

    I'm trying to solve a Krypto Problem on https://www.spoj.pl in Python, which involves console input.

    My Problem is, that the Input String has multiple Lines but is needed as one single String in the Programm. If I just use raw_input() and paste (for testing) the text in the console, Python threats it like I pressed enter after every Line -> I need to call raw_input() multiple times in a loop.

    The Problem is, that I cannot modify the Input String in any way, it doesn't have any Symbol thats marks the End and I don't know how many Lines there are.

    So what do I do?

  • Dreiven
    Dreiven almost 13 years
    I tried this, but unfortunately this doesn't seem to work. If I press Enter after pasting the Text, the programm still waits for more Input -> I need to press Enter in the new and empty Line. SPOJ seems to have similar behaviour.
  • Cat Plus Plus
    Cat Plus Plus almost 13 years
    @Dreiven: Strip the whitespace (raw_input().strip()).
  • Dreiven
    Dreiven almost 13 years
    I can't replace it like this because raw_input() is called for every Line seperately.
  • Andreas Jung
    Andreas Jung almost 13 years
    Then you have to collect your data into a buffer or a list....this is straight forward..
  • Cat Plus Plus
    Cat Plus Plus almost 13 years
    @Dreiven: You can try sys.stdin.read(), but it's likely that both this and above code will exhaust available memory.
  • Dreiven
    Dreiven almost 13 years
    I have to call raw_input() multiple times, once for each Line of my Input -> I don't know how many Lines there are -> I try PiotrLegnicas Solution -> The Loop won't terminate. Removing the breaks is really no Problem after I gathered all the Input.