Python input的使用

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

1 >>> x = input()
2 4.5
3 >>> type(x)
4 <class 'str'>
5 >>> y = input()
6 Do you love python?
7 >>> type(y)
8 <class 'str'>

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

1 >>> x = input()
2 abc
3 >>> x * 3
4 'abcabcabc'
5 >>> y = input()
6 123
7 >>> x + y
8 'abc123'

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是分割次数。

发布了47 篇原创文章 · 获赞 96 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/qq_41371349/article/details/104221712