前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python2 中 input() 和raw_input()

Python2 中 input() 和raw_input()

作者头像
py3study
发布2020-01-20 15:06:12
8570
发布2020-01-20 15:06:12
举报
文章被收录于专栏:python3python3

在 Python2 中如要想要获得用户从命令行的输入,可以使用 input() 和 raw_input() 两个函数,那么这两者有什么区别呢? 我们先借助 help 函数来看下两者的文档注释:

代码语言:javascript
复制
>>> help(raw_input)
Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

>>> help(input)
Help on built-in function input in module __builtin__:

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).

可以看出,raw_input() 返回的始终是一个“原始”(raw)字符串,并且去掉了行末的换行符。 值得注意的是,文档还提到“On Unix, GNU readline is used if enabled. ”, 这是说,如果 *nix 系统中安装了 GNU readline 库,并且在 python 中启用了(import readline),那么 raw_input() 底层就会调用这个库。 如果不启用,raw_input() 也能用,只不过会读取你键盘输入的所有字符,包括不可见字符,比如回退键……这样就很不方便了是不是。

而 input() 其实是在 raw_input() 返回的结果上再 调用了 eval() 函数,把原始字符串计算成 python 可以识别的对象。

在 Pyhon3 中,已经没有 raw_input() 函数了,而剩下 input() 函数与 Python2 中的 raw_input() 行为一致:

代码语言:javascript
复制
>>> help(raw_input)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined


>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档