开发者

Python command Line - multiple Line Input

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 Strin开发者_高级运维g 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?


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


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', '')


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,


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜