python中input函数的运行方式

发布时间:2020-08-06 11:04:30 作者:小新
来源:亿速云 阅读:281

这篇文章给大家分享的是有关python中input函数的运行方式的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

input()以字符串的方式获取用户输入:

>>> x = input()
4.5
>>> type(x)
<class 'str'>
>>> y = input()
Do you love python?
>>> type(y)
<class 'str'>

输入的字符串可以通过运算符进行连接、复制等操作:

>>> x = input()
abc
>>> x * 3
'abcabcabc'
>>> y = input()
123
>>> x + y
'abc123'

但无法直接参与算术运算,如:

>>> x = input()
5
>>> x + 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> x * 5
'55555'
>>> y = input()
6
>>> x * y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

此时可以使用转换,方法有多种:

1.指定类型转换

1 >>> y = int(input())
2 10
3 >>> type(y)
4 <class 'int'>

2.自动转换

函数eval() 用来执行一个字符串表达式,并返回表达式的值

eval(expression, globals[ ], locals[ ])

global 和 locals 分别相当于全局和局部变量,eval函数会优先在局部变量存储空间中检索

1  >>> y = eval(input())
2  4.5
3  >>> type(y)
4 <class 'float'>

3.切割转换

利用函数split()通过指定分隔符对字符串进行切片。

str.split(str="", num=string.count(str))

str为分割符,包括空格、\n,\t 等 ,num是分割次数。

感谢各位的阅读!关于python中input函数的运行方式就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. Python中input()函数漏洞及与raw_input()函数区别
  2. python中input()函数如何使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python npu

上一篇:JavaEE手写AOP实现,自动代理, AOP 面向切面的编程思想

下一篇:异地容灾备份是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》