Python 命令行 - 多行输入

发布于 2024-11-04 03:00:49 字数 321 浏览 6 评论 0原文

我正在尝试用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

宫墨修音 2024-11-11 03:00:49

当输入到达流末尾时,raw_input 将返回一个空字符串。因此,如果您确实需要累积整个输入(您可能应该避免给定的 SPOJ 约束),那么请执行以下操作:

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

    buffer += line

# process input

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
—━☆沉默づ 2024-11-11 03:00:49

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

最美的太阳 2024-11-11 03:00:49

由于 raw_input() 被设计为读取单行,因此您可能会遇到麻烦。
一个简单的解决方案是将输入字符串放入文本文件中并从那里进行解析。

假设您有 input.txt 您可以将值作为

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

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,
偏爱自由 2024-11-11 03:00:49

使用此处的最佳答案,您仍然会遇到应该处理的 EOF 错误。所以,我只是在这里添加了异常处理

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

    buffer += 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文