速戰速決 Python - python 數據類型: 數據類型轉換

速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd

速戰速決 Python - python 數據類型: 數據類型轉換

示例如下:

datatype/conversion.py

# python 數據類型轉換

a = 1
b = 3.14
# 隱式轉換,a 會被轉換爲 float 類型
c = a + b
print(c, type(c)) # 4.140000000000001 <class 'float'>

# 這個無法隱式轉換的,會報錯 can only concatenate str (not "int") to str
# print("123" + 123)
# 數字轉換爲字符串需要通過 str() 顯示轉換
print("123" + str(123)) # 123123

# 浮點型的顯示轉換
print(float("1")) # 1.0

# 整型的顯示轉換,取整數部分
print(int(1.2)) # 1
print(int(-1.2)) # -1
print(int("3")) # 3
# 注:無法像下面這樣將其轉換爲整型,需要先將其轉換爲浮點型,然後再轉爲整型
# print(int("3.14"))

# 布爾型的顯示轉換
print(bool(1)) # True
print(bool(0)) # False
print(bool(-1.2)) # True

d = [1, 2, 3]
# 列表轉換爲集合
e = set(d) # {1, 2, 3}
print(e)
# 集合轉換爲列表
f = list(e) # [1, 2, 3]
print(f)
# 列表轉換爲元組
g = tuple(f) # (1, 2, 3)
print(g)
# 元組轉換爲列表
h = list(g) # [1, 2, 3]
print(h)


速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章