python3 eval(input())

python3 中input()help 信息:

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.

input()读取的输入值都会转化为字符串。

>>> a = input()
123
>>> type(a)
<class 'str'>

如果我们要直接读取数值可以借助eval()帮忙。eval(source)可将source字符串的内容当作python表达式或代码执行(The source may be a string representing a Python expression or a code object as returned by compile().)

>>> a = eval(input())
123
>>> type(a)
<class 'int'>
>>> print(a)
123

简单的整型或许可以用工厂函数int():

>>> a = int(input())
123
>>> type(a)
<type 'int'>

但是eval()可以使用一些更复杂的对象,如set集合对象:

>>> a = input()
{1, 3, 4}
>>> type(a)
<class 'str'>
>>> a = eval(input())
{1, 3, 4}
>>> type(a)
<class 'set'>
>>> print(a)
{1, 3, 4}
posted @ 2017-03-24 00:45  Eliefly  阅读(5136)  评论(0)    收藏  举报