# Python 型態轉換
###### tags: `python`
created_time: 2020-11-17 15:30
updated_time: 2022-10-26 15:17:37.761131
[TOC]
## int
支持轉換為 int 類型的,僅有 float、str、bytes,其他類型均不支持。
### float -> int
會去掉小數點及後面的數值,僅保留整數部分。
```
int(-12.94) # -12
```
### str -> int
如果 字串 中有 數字(0-9) 和 正負號[+/-] 以外的字符,就會報錯。
```
int('1209') # 1209
int('-12') # -12
int('+1008') # 1008
```
### bytes -> int
如果 bytes 中有 數字(0-9) 和 正負號[+/-] 以外的字符,就會報錯。
```
int(b'1209') # 1209
int(b'-12') # -12
int(b'+1008') # 1008
```
## float
支持轉換為 float 類型的,僅有 int、str、bytes,其他類型均不支援。
### int -> float
int 轉換為 float 時,會自動給添加一位小數。
```
float(-1209) # -1209.0
```
### str -> float
如果 字串 中含有 正負號[+/-]、數字(0-9) 和 小數點(.) 以外的字符,則不支援轉換。
```
float('-1209') # -1209.0
float('-0120.29023') # -120.29023
```
### bytes -> float
如果 bytes 中含有 正負號[+/-]、數字(0-9) 和 小數點(.) 以外的字符,則不支援轉換。
```
float(b'-1209') # -1209.0
float(b'-0120.29023') # -120.29023
```
## complex
僅支持 int、float、str 轉換成 complex 類型。
### int -> complex
int 轉換 complex 時,會自動添加虛數部分並以 0j 表示。
```
complex(12) # (12+0j)
```
### float -> complex
float 轉換 complex 時,會自動添加虛數部分並以 0j 表示。
```
complex(-12.09) # (-12.09+0j)
```
### str -> complex
str 轉換 complex 時,如果能轉換成 int 或 float,則會轉換後再轉為 complex。如果字符串完全符合 complex 表達式規則,也可以轉換為 complex 類型值。
```
complex('-12.09') # (-12.09+0j)
complex('-12.0') # (-12+0j),去除了小數部分
complex('-12') # (-12+0j)
complex('-12+9j') # (-12+9j)
complex('(-12+9j)') # (-12+9j)
complex('-12.0-2.0j') # (-12-2j),去除了小數部分
complex('-12.0-2.09j') # (-12-2.09j)
complex(b'12') # 報錯,不支援 bytes 轉換為 complex
complex('12 + 9j') # 報錯,加號兩側不可有空格
```
## str
str() 函數可以將任意對象轉換為字符串。
### int -> str
```
str(12) # 12
```
### float -> str
float 轉換 str 會去除末位為 0 的小數部分。
```
str(-12.90) # -12.9
```
### complex -> str
complex 轉換str,會先將值轉化為標準的 complex 表達式,然後再轉換為字符串。
```
str(complex(12 + 9j)) # (12+9j)
str(complex(12, 9)) # (12+9j)
```
### bytes -> str
bytes 和str 的轉換比較特殊點,在Python 3.x 中,字符串和字節不再混淆,而是完全不同的數據類型。
轉換為可執行的表達式字符串:
```
str(b'hello world') # b'hello world'
```
str() 函數指定 encoding 參數。
或者使用 bytes.decode() 方法,可以作實際數據的轉換:
```
b'hello world'.decode() # hello world
str(b'hello world', encoding='utf-8') # hello world
str(b'\xe4\xb8\xad\xe5\x9b\xbd', encoding='utf-8') # 中国
```
### list -> str
會先將值格式化為標準的 list 表達式,然後再轉換為字符串。
```
str([]) # []
str([1, 2, 3]) # [1, 2, 3]
''.join(['a', 'b', 'c']) # abc
```
### tuple -> str
會先將值格式化為標準的 tuple 表達式,然後再轉換為字符串。
```
str(()) # ()
str((1, 2, 3)) # (1, 2, 3)
''.join(('a', 'b', 'c')) # abc
```
### dict -> str
會先將值格式化為標準的 dict 表達式,然後再轉換為字符串。
```
str({'name': 'hello', 'age': 18}) # {'name': 'hello', 'age': 18}
str({}) # {}
''.join({'name': 'hello', 'age': 18}) # nameage
```
### set -> str
會先將值格式化為標準的 set 表達式,然後再轉換為字符串。
```
str(set({})) # set()
str({1, 2, 3}) # {1, 2, 3}
''.join({'a', 'b', 'c'}) # abc
```
### 其他類型
轉換內置對象:
```
str(int) # <class 'int'>,轉換内置
str(hex) # <built-in function hex>,轉換內置函數
```
轉換類實例:
```
class Hello:
pass
obj = Hello()
print(str(obj))
# <__main__.Hello object at 0x1071c6630>
```
轉換函數:
```
def hello():
pass
print(str(hello))
# <function hello at 0x104d5a048>
```
## bytes
僅支持 str 轉換為 bytes 類型。
```
'測試'.encode() # b'\xe4\xb8\xad\xe5\x9b\xbd'
bytes('測試', encoding='utf-8') # b'\xe4\xb8\xad\xe5\x9b\xbd'
```
## list
支持轉換為 list 的類型,只能是序列,比如:str、tuple、dict、set等。
### str -> list
```
list('123abc') # ['1', '2', '3', 'a', 'b', 'c']
```
### bytes -> list
bytes 轉換列表,會取每個字節的 ASCII 十進制值並組合成列表
```
list(b'hello') # [104, 101, 108, 108, 111]
```
### tuple -> list
```
list((1, 2, 3)) # [1, 2, 3]
```
### dict -> list
字典轉換列表,會取鍵名作為列表的值。
```
list({'name': 'hello', 'age': 18}) # ['name', 'age']
```
### set -> list
```
list({1, 2, 3, 3, 2, 1}) # [1, 2, 3]
```
## tuple
與列表一樣,支持轉換為 tuple 的類型,只能是序列。
### str -> tuple
```
tuple('測試') # ('測', '試')
```
### bytes -> tuple
bytes 轉換元組,會取每個字節的ASCII 十進制值並組合成列表。
```
tuple(b'hello') # (104, 101, 108, 108, 111)
```
### list -> tuple
```
tuple([1, 2, 3]) # (1, 2, 3)
```
### dict -> tuple
```
tuple({'name': 'hello', 'age': 18}) # ('name', 'age')
```
### set -> tuple
```
tuple({1, 2, 3, 3, 2, 1}) # (1, 2, 3)
```
## dict
### str -> dict
1. 使用 json 模塊
```
使用 json 模塊轉換 JSON 字符串為字典時,需要求完全符合JSON 規範
尤其註意鍵和值只能由單引號包裹,否則會報錯。
```
```
import json
user_info = '{"name": "john", "gender": "male", "age": 28}'
print(json.loads(user_info))
# {'name': 'john', 'gender': 'male', 'age': 28}
```
2. 使用 eval 函數
因為 eval 函數能執行任何符合語法的表達式字符串,所以存在嚴重的安全問題,不建議。
```
user_info = "{'name': 'john', 'gender': 'male', 'age': 28}"
print(eval(user_info))
# {'name': 'john', 'gender': 'male', 'age': 28}
```
3. 使用 ast.literal_eval 方法
使用 ast.literal_eval 進行轉換既不存在使用 json 進行轉換的問題。
也不存在使用 eval 進行轉換的安全性問題,因此推薦使用 ast.literal_eval。
```
import ast
user_info = "{'name': 'john', 'gender': 'male', 'age': 28}"
user_dict = ast.literal_eval(user_info)
print(user_dict)
# {'name': 'john', 'gender': 'male', 'age': 28}
```
### list -> dict
通過 zip 將 2 個列表映射為字典:
```
list1 = [1, 2, 3, 4]
list2 = [1, 2, 3]
print(dict(zip(list1, list2)))
# {1: 1, 2: 2, 3: 3}
```
將嵌套的列表轉換為字典:
```
li = [
[1, 111],
[2, 222],
[3, 333],
]
print(dict(li))
# {1: 111, 2: 222, 3: 333}
```
### tuple -> dict
通過 zip 將 2 個元組映射為字典:
```
tp1 = (1, 2, 3)
tp2 = (1, 2, 3, 4)
print(dict(zip(tp1, tp2)))
# {1: 1, 2: 2, 3: 3}
```
將嵌套的元組轉換為字典:
```
tp = (
(1, 111),
(2, 222),
(3, 333),
)
print(dict(tp))
# {1: 111, 2: 222, 3: 333}
```
### set -> dict
通過 zip 將 2 個集合映射為字典:
```
set1 = {1, 2, 3}
set2 = {'a', 'b', 'c'}
print(dict(zip(set1, set2)))
# {1: 'c', 2: 'a', 3: 'b'}
```
## set
### str -> set
先將字符切割成元組,然後再去重轉換為集合。
```
print(set('hello')) # {'l', 'o', 'e', 'h'}
```
### bytes -> set
會取每個字節的 ASCII 十進制值並組合成元組,再去重。
```
set(b'hello') # {104, 108, 101, 111}
```
### list -> set
先對列表去重,再轉換。
```
set([1, 2, 3, 2, 1]) # {1, 2, 3}
```
### tuple -> set
先對列表去重,再轉換。
```
set((1, 2, 3, 2, 1)) # {1, 2, 3}
```
### dict -> set
會取字典的鍵名組合成集合。
```
set({'name': 'hello', 'age': 18})
# {'age', 'name'}
```