在 Python 中输入多行

Vaibhhav Khetarpal 2023年1月30日
  1. 在 Python 中使用 raw_input() 函数从用户那里获取多行输入
  2. 在 Python 中使用 sys.stdin.read() 函数从用户获取多行输入
在 Python 中输入多行

程序有时可能需要比默认单行输入长得多的输入。本教程演示了在 Python 中从用户那里获取多行输入的各种可用方法。

在 Python 中使用 raw_input() 函数从用户那里获取多行输入

raw_input() 函数可用于在 Python 2 中接收来自用户的用户输入。但是,单独使用此函数并不能实现手头的任务。让我们继续展示如何在 Python 中以正确的方式实现这个函数。

以下代码使用 raw_input() 函数从 Python 中的用户获取多行输入。

x = ""  # The string is declared
for line in iter(raw_input, x):
    pass

此外,在引入 Python 3 之后,raw_input() 函数变得过时并被新的 input() 函数取代。

因此,如果使用 Python 3 或更高版本,我们可以使用 input() 函数而不是 raw_input() 函数。

可以简单地调整上面的代码,使其在 Python 3 中可用。

x = ""  # The string is declared
for line in iter(input, x):
    pass

在 Python 中使用 sys.stdin.read() 函数从用户获取多行输入

sys 模块可以导入到 Python 代码中,主要用于维护和操作 Python 运行时环境。

sys.stdin.read() 函数就是这样一个函数,它是 sys 模块的一部分,可用于在 Python 2 和 Python 3 中从用户那里获取多行输入。

import sys

s = sys.stdin.read()
print(s)

Python 控制台可以在输入后清除并使用 print 命令显示在屏幕上。

Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

相关文章 - Python Input