1. 程式人生 > >python中,如何將字串轉換為數字(將數字轉換為整型),字串的10轉換為整型的10,10.5轉換為10

python中,如何將字串轉換為數字(將數字轉換為整型),字串的10轉換為整型的10,10.5轉換為10

說明

  在實際的應用過程中,有的時候可能會遇到字串的10,需要將字串的10轉換為數字的10

  在此記錄下,通過int函式轉換的過程。

操作過程

1.將字串轉換為整型的10

>>> str1 = "10"        #將一個字串的10賦給變數str1
>>> type(str1)
<class 'str'>           #通過type函式查出來型別是str
>>> int1 = int(str1)    #通過int函式,轉換為了int型別的10
>>> type(int1)
<class
'int'> >>> int1 10

 2.如果不傳任何的引數,int的結果是0

>>> int()
0

 3.如果傳入的是小數,轉換的結果是沒有小數部分

>>> int(10.0)
10
>>> int(10.5)
10
>>> int(-10.5)
-10
>>> int(-10.0)
-10

備註:無論傳入的正數,還是負數,都會將小數部分去掉,符號保留。

 

int()函式的官方解釋

    def __init__
(self, x, base=10): # known special case of int.__init__ """ int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 # (copied from class doc)
""" pass

 

文件建立時間:2018年12月7日16:53:32