溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python不同數(shù)據(jù)類型間如何轉(zhuǎn)換

發(fā)布時(shí)間:2022-03-04 16:11:24 來源:億速云 閱讀:129 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Python不同數(shù)據(jù)類型間如何轉(zhuǎn)換的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Python不同數(shù)據(jù)類型間如何轉(zhuǎn)換文章都會(huì)有所收獲,下面我們一起來看看吧。

字符串與數(shù)字類型的轉(zhuǎn)換

什么是類型轉(zhuǎn)換?—> 將自身的數(shù)據(jù)類型變成新的數(shù)據(jù)類型,并擁有新的數(shù)據(jù)類型的所有功能的過程即為類型轉(zhuǎn)換

為什么做類型轉(zhuǎn)換?—> 為了方便更好的幫助處理業(yè)務(wù),將類型變更為更適合業(yè)務(wù)場景的類型

舉例:比如 a = '1' ,這是一個(gè)字符串類型,所以它無法執(zhí)行數(shù)字類型的操作。

字符串與數(shù)字之間轉(zhuǎn)換的要求

str —> number :必須是由數(shù)字組成的字符串才可以通過類型轉(zhuǎn)換轉(zhuǎn)為數(shù)字類型

int_str = '1024' ; float_str = '3.1415926'

number —> str : 無任何要求

字符串與數(shù)字之間的轉(zhuǎn)換函數(shù)

原始類型目標(biāo)類型函數(shù)舉例
整型字符串strnew_str = str(123456)
浮點(diǎn)型字符串strnew_str = str(3.1515926)
字符串整型intnew_int = int(‘1234’)
字符串浮點(diǎn)型intnew_float = int(‘3.1415926’)

示例如下:

str_int = '1024'
new_int = int(int_str)
print(new_int)

# 執(zhí)行結(jié)果如下:
# >>> 1024
# >>> <class 'int'>


int_str = 3.1415926
new_str = str(int_str)
print(new_str)
print(type(new_str))

# 執(zhí)行結(jié)果如下:
# >>> 3.1415926
# >>> <class 'str'>


int_and_str = '123abc'			# 只有數(shù)字組成的字符串才可以通過類型轉(zhuǎn)換轉(zhuǎn)為數(shù)字類型
new_int = int(int_and_str)
print(new_int)

# 執(zhí)行結(jié)果如下:
# >>> ValueError: invalid literal for int() with base 10: '123abc'

字符串與列表之間的轉(zhuǎn)換

split() 函數(shù) - 字符串轉(zhuǎn)列表

split() 函數(shù) 的功能:將字符串以一定的規(guī)則切割,并轉(zhuǎn)換成列表。

split() 函數(shù) 的用法:string.split(sep=Node, maxsplit=-1) ;

  • sep : 為作為切割識(shí)別的規(guī)則符號(hào),不填寫的情況下默認(rèn)切割規(guī)則符號(hào)為空格;如果字符串不存在空格,則不分割成列表。

  • maxsplit:將字符串以切割規(guī)則符號(hào)切割的次數(shù),默認(rèn)為 -1 , 即不限制次數(shù)。

  • split() 函數(shù) 的 返回值為列表

示例如下:

name = 'My name is Neo'
name_list = name.split()

print(name_list)

# 執(zhí)行結(jié)果如下:
# >>> ['My', 'name', 'is', 'Neo']
# >>> 可以看到已經(jīng)將 'name' 以空格為切割規(guī)則符號(hào)切割成了每個(gè)單詞為一個(gè)元素的列表


test_int = '1,  2,    3,     4'
test_int_list = test_int.split(',')

print(test_int_list)

# 執(zhí)行結(jié)果如下:
# >>> ['1', '  2', '    3', '     4']
# >>> 可以看到已經(jīng)將 'test_int' 以逗號(hào)為切割規(guī)則符號(hào)切割成了每個(gè)單詞為一個(gè)元素的列表


test_str = 'a|b|c|d|e'
test_str_list = test_str.split('|', 2)

print(test_str_list)

# 執(zhí)行結(jié)果如下:
# >>> ['a', 'b', 'c|d|e']
# >>> 可以看到已經(jīng)將 'test_str_list' 以 '|' 為切割規(guī)則符號(hào)切割成了兩次


error_str = ' a~b~c '
test_error_str = error_str.split('')
print(test_error_str)

# 執(zhí)行結(jié)果如下:
# >>> ValueError: empty separator			注意:split()函數(shù)是不可以用空字符串作為切割規(guī)則符號(hào)的

join() 函數(shù) - 列表轉(zhuǎn)字符串

split() 函數(shù) 的功能:將列表以一定的規(guī)則切割,并轉(zhuǎn)換成字符串。

split() 函數(shù) 的用法:'sep'.join(iterable) ;

  • sep:生成字符串用來分割列表每個(gè)元素的符號(hào)

  • iterable:非數(shù)字類型的列表或元組或集合

  • join() 函數(shù) 的 返回值為一個(gè)字符串

  • 需要注意的是:只有列表的元素為字符串的情況下才可以將列表轉(zhuǎn)為字符串,列表元素為 數(shù)字、元組、字典等數(shù)據(jù)類型的情況下,則會(huì)報(bào)錯(cuò)。

示例如下:

test_info = ['a', 'b', 'c']
new_info = '-'.join(test_info)

print(new_info)

# 執(zhí)行結(jié)果如下:
# >>> a-b-c


test_info_int = [1, 2, 3, 4]
new_info_int = '-'.join(test_info_int)

print(new_info_int)

# 執(zhí)行結(jié)果如下:
# >>> TypeError: sequence item 0: expected str instance, int found


test_info_tuple = [(1, ), (2, 3, 4)]
new_info_tuple= '-'.join(test_info_tuple)

print(new_info_tuple)

# 執(zhí)行結(jié)果如下:
# >>> TypeError: sequence item 0: expected str instance, int found

數(shù)據(jù)類型轉(zhuǎn)換 - 小練習(xí)

將字符串 'a e f h j k d l' , 轉(zhuǎn)換為列表并進(jìn)行排序,然后再轉(zhuǎn)為字符串。

代碼示例如下:

sort_str = 'a e f h j k d l'
sort_str_list = sort_str.split(' ')
print(sort_str_list)

# 執(zhí)行結(jié)果如下:
# >>> ['a', 'e', 'f', 'h', 'j', 'k', 'd', 'l']

sort_str_list.sort()
print(sort_str_list)

# 執(zhí)行結(jié)果如下:
# >>> ['a', 'd', 'e', 'f', 'h', 'j', 'k', 'l']

sort_str = '|'.join(sort_str_list)
print(sort_str)
print(type(sort_str))

# 執(zhí)行結(jié)果如下:
# >>> a|d|e|f|h|j|k|l
# >>> <class 'str'>

拓展 - sorted() 函數(shù)

sorted() 函數(shù)區(qū)別于 sort() 函數(shù)。sort() 函數(shù)為列表的內(nèi)置函數(shù),而sorted() 函數(shù)為python的內(nèi)置函數(shù),可以處理所有的數(shù)據(jù)類型。

示例如下:

sort_str_new = 'aefhjkdc'
result = sorted(sort_str_new)

print(result)

# 執(zhí)行結(jié)果如下:
# >>> ['a', 'c', 'd', 'e', 'f', 'h', 'j', 'k']


print(''.join(result))

# 執(zhí)行結(jié)果如下:
# >>> acdefhjk

字符串與bytes通過編解碼進(jìn)行轉(zhuǎn)換

什么是 bytes ?(比特類型) &mdash;> bytes 是一種二進(jìn)制數(shù)據(jù)流,也是一種可傳輸?shù)念愋停诟鱾€(gè)編程語言中都存在。也可以認(rèn)為它是一種特殊的字符串,因?yàn)樗L得和字符串幾乎一模一樣,同時(shí)也擁有字符串幾乎所有的內(nèi)置函數(shù)。我們完全可以像操作字符串一樣操作 比特類型 (bytes),只不過字符串前需要加上 b 的標(biāo)識(shí)。

示例如下:

bt = b'my name is Neo'
print('\'bt\'的值為:', bt, ';\'bt\'的類型為:', type(bt))

# 執(zhí)行結(jié)果如下:
# >>> 'bt'的值為: b'my name is Neo' ;'bt'的類型為: <class 'bytes'>


print(bt.capitalize())

# 執(zhí)行結(jié)果如下:
# >>> b'My name is neo'


print(bt.replace('Neo', 'Jack'))

# 執(zhí)行結(jié)果如下:
# >>> TypeError: a bytes-like object is required, not 'str'    這里的報(bào)錯(cuò)是因?yàn)槲覀兲鎿Q的類型為字符串類型,正確的寫法如下


print(bt.replace(b'Neo', b'Jack'))

# 執(zhí)行結(jié)果如下:
# >>> b'my name is Jack'


print(bt[0])
print(bt[-1])
print(bt[3:8])

# 執(zhí)行結(jié)果如下:
# >>> 109		這里的109是 'n' 的二進(jìn)制流的顯示方式
# >>> 111		這里的111是 'o' 的二進(jìn)制流的顯示方式
# >>> b'name '	


print('\'N\'字符的索引位置為:', bt.find(b'N'))

# 執(zhí)行結(jié)果如下:
# >>> 'N'字符的索引位置為: 11


test_info = b'my name is \'李雷\''
print(test_info)

# 執(zhí)行結(jié)果如下:
# >>> SyntaxError: bytes can only contain ASCII literal characters.    # 報(bào)錯(cuò)信息為"bytes"類型只支持ASCII碼的字符
# 由此也引出了下文的 encode() 函數(shù) 與 decode() 函數(shù)

encode() 函數(shù) - 字符串轉(zhuǎn) bytes

encode() 函數(shù) 的功能:將字符串轉(zhuǎn)為比特(byte)類型

encode() 函數(shù) 用法:

用法:string.encode(encoding='utf-8', errors='strict')

參數(shù):encoding 與 errors

  • encoding 轉(zhuǎn)換成的編碼格式,如ascii、gbk、默認(rèn)為 &lsquo;utf-8&rsquo;

  • errors 出錯(cuò)時(shí)的處理方法,默認(rèn)為 strict ;直接報(bào)錯(cuò)誤,也可以選擇 ignore 忽律錯(cuò)誤

  • 返回值為一個(gè)比特(bytes)類型

示例如下:

test_str = 'my name is HanMeimei'
bytes_str = test_str.encode('utf-8')
print(bytes_str)
print(type(bytes_str))

# 執(zhí)行結(jié)果如下:
# >>> b'my name is HanMeimei'
# >>> <class 'bytes'>

decode() 函數(shù) - bytes 轉(zhuǎn)字符串

decode() 函數(shù) 的功能:將比特(byte)類型轉(zhuǎn)為字符串

decode() 函數(shù) 用法:

用法:string.encode(encoding='utf-8', errors='strict') ;

參數(shù):encoding 與 errors; 注意,這里的 encoding 是解碼的作用,encode() 函數(shù) 的 encoding 是 編碼的作用。

  • encoding 轉(zhuǎn)換成的編碼格式,如ascii、gbk、默認(rèn)為 &lsquo;utf-8&rsquo;

  • errors 出錯(cuò)時(shí)的處理方法,默認(rèn)為 strict ;直接報(bào)錯(cuò)誤,也可以選擇 ignore 忽律錯(cuò)誤

  • 返回值為一個(gè)字符串類型

示例如下:

bytes_str = b'Python is very good'
test_str = bytes_str.decode('utf-8')
print(test_str)
print(type(test_str))

# 執(zhí)行結(jié)果如下:
# >>> Python is very good
# >>> <class 'str'>
str_date = 'my name is \'亞當(dāng)\''
byte_date = str_date.encode('utf-8')
print(byte_date)

# 執(zhí)行結(jié)果如下:
# >>> b"my name is '\xe4\xba\x9a\xe5\xbd\x93'"  這是 utf-8 轉(zhuǎn)化的中文的樣子

print(byte_date.decode('utf-8'))

# 執(zhí)行結(jié)果如下:
# >>> my name is '亞當(dāng)'

列表、集合、元組的轉(zhuǎn)換

列表元組集合間轉(zhuǎn)換的函數(shù)

原始類型目標(biāo)類型函數(shù)舉例
列表集合setnew_set = set([1, 2, 3, 4, 5])
列表元組tuplenew_tuple = ([1, 2, 3, 4, 5]
元組集合setnew_set = set((1, 2, 3, 4, 5))
元組列表listnew_set = set((1, 2, 3, 4, 5))
集合列表listnew_list = list({1, 2, 3, 4, 5})
集合元組tuplenew_tuple = tuple({1, 2, 3, 4, 5})

關(guān)于“Python不同數(shù)據(jù)類型間如何轉(zhuǎn)換”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Python不同數(shù)據(jù)類型間如何轉(zhuǎn)換”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI