发布时间:2022-10-24 09:40:31 人气:213 作者:多测师
python的input函数运行:
input()以字符串的方式获取用户输入:
>>> x = input()
4.5
>>> type(x)
>>> y = input()
Do you love python?
>>> type(y)
输入的字符串可以通过运算符进行连接、复制等操作:
>>> x = input()
abc
>>> x * 3
'abcabcabc'
>>> y = input()
123
>>> x + y
'abc123'
但无法直接参与算术运算,如:
>>> x = input()
5
>>> x + 5
Traceback (most recent call last):
File "", line 1, in
TypeError: must be str, not int
>>> x * 5
'55555'
>>> y = input()
6
>>> x * y
Traceback (most recent call last):
File "", line 1, in
TypeError: can't multiply sequence by non-int of type 'str'
此时可以使用转换,方法有多种:
1.指定类型转换
1 >>> y = int(input())
2 10
3 >>> type(y)
4
2.自动转换
函数eval() 用来执行一个字符串表达式,并返回表达式的值
eval(expression, globals[ ], locals[ ])
global 和 locals 分别相当于全局和局部变量,eval函数会优先在局部变量存储空间中检索
1 >>> y = eval(input())
2 4.5
3 >>> type(y)
4
3.切割转换
利用函数split()通过指定分隔符对字符串进行切片。
str.split(str="", num=string.count(str))
str为分割符,包括空格、\n,\t 等 ,num是分割次数。
以上内容为大家介绍了python培训之input函数如何运行,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/