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 >>> x = input() 2 5 3 >>> x + 5 4 Traceback (most recent call last): 5 File "<stdin>", line 1, in <module> 6 TypeError: must be str, not int 7 >>> x * 5 8 '55555' 9 >>> y = input() 10 6 11 >>> x * y 12 Traceback (most recent call last): 13 File "<stdin>", line 1, in <module> 14 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是分割次數。