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'
(更多学习内容,请点击python学习网)
但无法直接参与算术运算,如:
>>> 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是分割次数。
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!