Python3 類型轉換

INT

支持轉換爲INT類型的,僅有  floatstrbytes,其他類型均不支持。

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

浮動

支持轉換爲浮動類型的,僅有  intstrbytes,其他類型均不支持。

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

複雜

僅支持  intfloatstr 轉換成複雜的類型。

int - >複雜

int轉換complex時,會自動添加虛數部分並以0j表示。

complex(12)         # (12+0j)

浮動 - >複雜

float轉換complex時,會自動添加虛數部分並以0j表示。

complex(-12.09)     # (-12.09+0j)

str - >複雜

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() 函數可以將任意對象轉換爲字符串。

int - > str

int轉換str會直接完全轉換。

str(12)     # 12

float - > str

float轉換str會去除末位爲0的小數部分。

str(-12.90)     # -12.9

複雜 - > 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}

元組 - >字典

通過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}

設置 - > dict

通過zip將2個集合映射爲字典:

set1 = {1, 2, 3}
set2 = {'a', 'b', 'c'}

print(dict(zip(set1, set2)))

# {1: 'c', 2: 'a', 3: 'b'}

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}

元組 - >設置

先對列表去重,再轉換。

set((1, 2, 3, 2, 1))    # {1, 2, 3}

dict - >設置

會取字典的鍵名組合成集合。

set({'name': 'hello', 'age': 18})

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