Python 命令行 - 多行输入
我正在尝试用 Python 解决 https://www.spoj.pl 上的加密问题,其中涉及控制台输入。
我的问题是,输入字符串有多行,但在程序中需要作为一个字符串。 如果我只是使用 raw_input() 并将文本粘贴(用于测试)到控制台中,Python 就会威胁它,就像我在每一行之后按 Enter 键 ->我需要在循环中多次调用 raw_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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当输入到达流末尾时,raw_input 将返回一个空字符串。因此,如果您确实需要累积整个输入(您可能应该避免给定的 SPOJ 约束),那么请执行以下操作:
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:
由于 Windows 上的行尾在 Unix 系统上标记为 '\r\n' 或 '\n' ,因此可以直接使用
your_input.replace('\r\n', '')替换这些字符串
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', '')
由于
raw_input()
被设计为读取单行,因此您可能会遇到麻烦。一个简单的解决方案是将输入字符串放入文本文件中并从那里进行解析。
假设您有 input.txt 您可以将值作为
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
使用此处的最佳答案,您仍然会遇到应该处理的 EOF 错误。所以,我只是在这里添加了异常处理
Using the best answer here, you will still have an EOF error that should be handled. So, I just added exception handling here