Python 中的數據類型轉換核心分為 隱式轉換(解釋器自動完成)和 顯式轉換(通過內置函數手動實現),轉換需遵循 “兼容原則”(如字符串需是合法格式才能轉數值)。以下是分類清晰的轉換方法、示例及注意事項:

一、隱式類型轉換(自動完成,無需手動干預)

解釋器根據運算場景自動轉換類型,優先向 “更包容” 的類型轉換(避免數據丟失),常見場景如下:

1. 數值類型之間的自動轉換

  • 整數(int)↔ 浮點數(float):運算時 int 自動轉 float
  • 布爾值(bool)↔ 數值:True 等價於 1,False 等價於 0,參與運算時自動轉 int/float

示例:

python運行

# int → float(運算結果為 float)
print(10 + 3.14)  # 13.14(int 10 自動轉 float)
print(5 * False)  # 0(bool 轉 int)
print(3.5 + True) # 4.5(bool 轉 float)

# 複數與其他數值運算:其他數值轉 complex
print(2 + 3j + 5) # (7+3j)(int 5 轉 complex)

2. 注意:隱式轉換的限制

  • 字符串(str)不能與數值自動轉換(如 '5' + 10 會報錯,需顯式轉換)
  • 集合、字典等無序類型不支持與序列 / 數值自動轉換

二、顯式類型轉換(手動調用內置函數,核心場景)

通過 Python 內置函數主動轉換類型,需確保轉換 “合法”(如不能把 'abc' 轉整數),常用轉換函數及場景如下:

1. 核心轉換函數速查表

轉換函數

功能描述

合法輸入示例

輸出結果

int(x)

轉整數(x 可為 float/str/bool)

int(3.14)、int('100')、int(True)

3、100、1

float(x)

轉浮點數(x 可為 int/str/bool)

float(5)、float('3.14')、float(False)

5.0、3.14、0.0

bool(x)

轉布爾值(所有類型均可轉)

bool(0)、bool('')、bool([1,2])

False、False、True

str(x)

轉字符串(所有類型均可轉)

str(123)、str(3.14)、str([1,2])

'123'、'3.14'、'[1, 2]'

list(x)

轉列表(x 可為序列 / 可迭代對象)

list('abc')、list((1,2))、list({3,4})

['a','b'], [1,2], [3,4]

tuple(x)

轉元組(x 可為序列 / 可迭代對象)

tuple([1,2])、tuple('abc')

(1,2)、('a','b','c')

set(x)

轉集合(x 可為可迭代對象,去重)

set([1,2,2])、set('aab')

{1,2}、{'a','b'}

dict(x)

轉字典(x 需為鍵值對序列)

dict([('a',1), ('b',2)])

{'a':1, 'b':2}

bytes(x, enc)

字符串轉字節串(需指定編碼,如 utf-8)

bytes (' 中文 ', 'utf-8')

b'\xe4\xb8\xad\xe6\x96\x87'

2. 常用顯式轉換場景示例

(1)數值類型 ↔ 字符串(最常用)

python運行

# 數值 → 字符串(str() 萬能)
num1 = 123
str1 = str(num1)  # '123'(int→str)
num2 = 3.14
str2 = str(num2)  # '3.14'(float→str)

# 字符串 → 數值(需確保字符串是合法數值格式)
str3 = '456'
num3 = int(str3)   # 456(str→int)
str4 = '7.89'
num4 = float(str4) # 7.89(str→float)

# 進階:字符串含特殊格式(如千分位),需先處理
str5 = '1,234'
num5 = int(str5.replace(',', ''))  # 1234(先去除逗號再轉int)

(2)序列類型之間轉換(list/tuple/str)

序列類型(有序、可迭代)可直接通過 list()/tuple()/str() 互轉:

python運行

# 字符串 ↔ 列表/元組
s = 'hello'
lst = list(s)    # ['h','e','l','l','o'](str→list)
tup = tuple(s)   # ('h','e','l','l','o')(str→tuple)
s2 = ''.join(lst)# 'hello'(list→str,需用 join())

# 列表 ↔ 元組
lst1 = [1,2,3]
tup1 = tuple(lst1)  # (1,2,3)(list→tuple)
lst2 = list(tup1)   # [1,2,3](tuple→list)

(3)集合 / 字典相關轉換

python運行

# 列表 → 集合(自動去重)
lst = [1,2,2,3,3,3]
s = set(lst)  # {1,2,3}(去重效果)

# 字典相關轉換(鍵/值提取)
d = {'name': 'Tom', 'age': 18}
keys = list(d.keys())    # ['name', 'age'](字典鍵轉列表)
values = tuple(d.values())# (18, 'Tom')(字典值轉元組)
items = list(d.items())  # [('name','Tom'), ('age',18)](鍵值對轉列表)

# 鍵值對序列 → 字典
kv_list = [('a', 1), ('b', 2)]
d2 = dict(kv_list)  # {'a':1, 'b':2}

(4)布爾值轉換(所有類型均可轉)

遵循 “空 / 零為 False,非空 / 非零為 True” 原則:

python運行

print(bool(0))        # False(數值0)
print(bool(3.14))     # True(非零數值)
print(bool(''))       # False(空字符串)
print(bool('abc'))    # True(非空字符串)
print(bool([]))       # False(空列表)
print(bool([1]))     # True(非空列表)
print(bool(None))     # False(空值)

(5)字節串與字符串轉換(文件 / 網絡傳輸常用)

python運行

# 字符串 → 字節串(encode 編碼)
s = 'Python編程'
b = s.encode('utf-8')  # b'Python\xe7\xbc\x96\xe7\xa8\x8b'(utf-8編碼)

# 字節串 → 字符串(decode 解碼,需與編碼一致)
s2 = b.decode('utf-8')  # 'Python編程'(解碼回原字符串)

3. 轉換失敗的常見情況與解決方案

(1)字符串轉數值失敗(格式不合法)

python運行

# 錯誤示例:字符串含非數字字符
int('12a3')  # 報錯 ValueError: invalid literal for int() with base 10: '12a3'

# 解決方案:先判斷是否合法(用 isdigit() 或 try-except)
def str_to_int(s):
    if s.isdigit():  # 判斷是否全為數字字符
        return int(s)
    else:
        return None

print(str_to_int('123'))  # 123
print(str_to_int('12a3')) # None

# 更通用的處理(兼容負數、浮點數字符串)
def safe_convert(s, target_type):
    try:
        return target_type(s)
    except (ValueError, TypeError):
        return None

print(safe_convert('-45.6', float))  # -45.6
print(safe_convert('abc', int))      # None

(2)字典轉換失敗(輸入非鍵值對序列)

python


運行





dict([1,2,3])  # 報錯 ValueError: dictionary update sequence element #0 has length 1; 2 is required
# 正確示例:必須是鍵值對(長度為2的序列)
dict([('a',1), ('b',2)])  # 合法
dict(zip(['a','b'], [1,2]))# 合法(zip生成鍵值對)

三、轉換核心原則與注意事項

  1. 兼容性優先:只有 “語義兼容” 的類型才能轉換(如 list() 不能轉字典,需先整理為鍵值對);
  2. 避免數據丟失
  • int(3.99) 會直接捨棄小數部分(結果為 3),而非四捨五入;
  • 元組轉列表會丟失 “不可變” 特性,列表轉集合會丟失順序和重複元素;
  1. 編碼一致性:字節串與字符串轉換時,編碼(如 utf-8)和解碼必須一致,否則報錯 UnicodeDecodeError
  2. 異常處理:不確定輸入是否合法時,用 try-except 捕獲轉換異常(如 ValueErrorTypeError)。

四、總結

  1. 簡單轉換(如數值↔字符串、序列互轉)用 str()/int()/list() 等內置函數,直接高效;
  2. 複雜轉換(如帶格式的字符串、非法輸入)需先預處理(如替換字符)或用 try-except 保障穩定性;
  3. 隱式轉換僅發生在兼容的數值類型之間,大部分場景需顯式轉換,核心是 “明確轉換目標和輸入合法性”。