史上最全的 Python 3 類型轉換指南

int

支持轉換爲 int 類型的,僅有 floatstrbytes,其餘類型均不支持。python

float -> int

會去掉小數點及後面的數值,僅保留整數部分。json

int(-12.94)     # -12

str -> int

若是字符串中有數字(0-9)和正負號(+/-)之外的字符,就會報錯。segmentfault

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 類型的,僅有 intstrbytes,其餘類型均不支持。函數

int -> float

int 轉換爲 float 時,會自動給添加一位小數。post

float(-1209)     # -1209.0

str -> float

若是字符串含有正負號(+/-)、數字(0-9)和小數點(.)之外的字符,則不支持轉換。ui

float('-1209')          # -1209.0
float('-0120.29023')    # -120.29023

bytes -> float

若是 bytes 中含有正負號(+/-)、數字(0-9)和小數點(.)之外的字符,則不支持轉換。.net

float(b'-1209')         # -1209.0
float(b'-0120.29023')   # -120.29023

complex

僅支持 intfloatstr 轉換成 complex 類型。code

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

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

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

  • 使用 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}
  • 使用 eval 函數

    由於 eval 函數能執行任何符合語法的表達式字符串,因此存在嚴重的安全問題,不建議。
    user_info = "{'name': 'john', 'gender': 'male', 'age': 28}"
    print(eval(user_info))
    
    # {'name': 'john', 'gender': 'male', 'age': 28}
  • 使用 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'}

參考資料


原文地址: https://shockerli.net/post/py...

更多文章請訪問個人我的博客: https://shockerli.net

相關文章
相關標籤/搜索