Mac*_*jPL 24 python input multiline
我想编写一个程序来获取多行输入并逐行处理它.为什么没有像raw_inputPython 3 那样的功能?
input不允许用户放置由换行符(\n Enter)分隔的行,它只打印回第一行.
它可以存储在变量中,甚至可以读取到列表中吗?
小智 36
raw_input 可以正确处理EOF,所以我们可以写一个循环,直到我们收到用户的EOF(Ctrl-D):
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
Run Code Online (Sandbox Code Playgroud)
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
Run Code Online (Sandbox Code Playgroud)
Zda*_*daR 30
在Python 3.x中raw_input(),Python 2.x已被input()函数取代.但是在这两种情况下你都不能输入多行字符串,为此你需要逐行从用户那里获取输入然后.join()使用它们\n,或者你也可以使用各种行并使用+运算符分隔它们来连接它们.\n
要从用户获得多行输入,您可以像:
no_of_lines = 5
lines = ""
for i in xrange(5):
lines+=input()+"\n"
print lines
Run Code Online (Sandbox Code Playgroud)
要么
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
Run Code Online (Sandbox Code Playgroud)
che*_*ner 10
input(prompt) 基本上相当于
def input(prompt):
print(prompt, end='', file=sys.stderr)
return sys.stdin.readline()
Run Code Online (Sandbox Code Playgroud)
sys.stdin如果您愿意,可以直接阅读。
lines = sys.stdin.readlines()
lines = [line for line in sys.stdin]
five_lines = list(itertools.islice(sys.stdin, 5))
Run Code Online (Sandbox Code Playgroud)
前两个要求输入以某种方式结束,要么到达文件末尾,要么用户键入 Control-D(或 Windows 中的 Control-Z)以表示结束。无论是从文件还是从终端/键盘读取五行后,最后一行都会返回。
| 归档时间: |
|
| 查看次数: |
110061 次 |
| 最近记录: |