Python學(xué)習(xí)之不同數(shù)據(jù)類型間的轉(zhuǎn)換總結(jié)
字符串與數(shù)字類型的轉(zhuǎn)換
什么是類型轉(zhuǎn)換?—> 將自身的數(shù)據(jù)類型變成新的數(shù)據(jù)類型,并擁有新的數(shù)據(jù)類型的所有功能的過(guò)程即為類型轉(zhuǎn)換
為什么做類型轉(zhuǎn)換?—> 為了方便更好的幫助處理業(yè)務(wù),將類型變更為更適合業(yè)務(wù)場(chǎng)景的類型
舉例:比如 a = '1' ,這是一個(gè)字符串類型,所以它無(wú)法執(zhí)行數(shù)字類型的操作。
字符串與數(shù)字之間轉(zhuǎn)換的要求
str —> number :必須是由數(shù)字組成的字符串才可以通過(guò)類型轉(zhuǎn)換轉(zhuǎn)為數(shù)字類型
int_str = '1024' ; float_str = '3.1415926'
number —> str : 無(wú)任何要求
字符串與數(shù)字之間的轉(zhuǎn)換函數(shù)
| 原始類型 | 目標(biāo)類型 | 函數(shù) | 舉例 |
|---|---|---|---|
| 整型 | 字符串 | str | new_str = str(123456) |
| 浮點(diǎn)型 | 字符串 | str | new_str = str(3.1515926) |
| 字符串 | 整型 | int | new_int = int(‘1234’) |
| 字符串 | 浮點(diǎn)型 | int | new_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ù)字組成的字符串才可以通過(guò)類型轉(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),不填寫(xiě)的情況下默認(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:生成字符串用來(lái)分割列表每個(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通過(guò)編解碼進(jìn)行轉(zhuǎn)換
什么是 bytes ?(比特類型) —> bytes 是一種二進(jìn)制數(shù)據(jù)流,也是一種可傳輸?shù)念愋停诟鱾€(gè)編程語(yǔ)言中都存在。也可以認(rèn)為它是一種特殊的字符串,因?yàn)樗L(zhǎng)得和字符串幾乎一模一樣,同時(shí)也擁有字符串幾乎所有的內(nèi)置函數(shù)。我們完全可以像操作字符串一樣操作 比特類型 (bytes),只不過(guò)字符串前需要加上 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的類型為字符串類型,正確的寫(xiě)法如下
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)為 ‘utf-8’
- 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)為 ‘utf-8’
- 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ù) | 舉例 |
|---|---|---|---|
| 列表 | 集合 | set | new_set = set([1, 2, 3, 4, 5]) |
| 列表 | 元組 | tuple | new_tuple = ([1, 2, 3, 4, 5] |
| 元組 | 集合 | set | new_set = set((1, 2, 3, 4, 5)) |
| 元組 | 列表 | list | new_set = set((1, 2, 3, 4, 5)) |
| 集合 | 列表 | list | new_list = list({1, 2, 3, 4, 5}) |
| 集合 | 元組 | tuple | new_tuple = tuple({1, 2, 3, 4, 5}) |
到此這篇關(guān)于Python學(xué)習(xí)之不同數(shù)據(jù)類型間的轉(zhuǎn)換總結(jié)的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)類型轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于keras中keras.layers.merge的用法說(shuō)明
這篇文章主要介紹了關(guān)于keras中keras.layers.merge的用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
如何在pycharm中配置pyqt5設(shè)計(jì)GUI操作教程
這篇文章主要介紹了如何在pycharm中配置pyqt5設(shè)計(jì)GUI的操作教程,有需要的朋友可以借鑒參考下,希望大家可以多多交流,討論相關(guān)問(wèn)題共同提升2021-08-08
python3使用diagrams繪制架構(gòu)圖的步驟
這篇文章主要介紹了python3使用diagrams生成架構(gòu)圖的步驟,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
Python3中在Anaconda環(huán)境下安裝basemap包
今天小編就為大家分享一篇關(guān)于Python3中在Anaconda環(huán)境下安裝basemap包的文章,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10
利用Python?Matlab繪制曲線圖的簡(jiǎn)單實(shí)例
們經(jīng)常會(huì)遇到這種情況,有一個(gè)數(shù)學(xué)函數(shù),我們希望了解他的圖像,這個(gè)時(shí)候使用python 的matplotlib就可以幫助我們,下面這篇文章主要介紹了利用Python?Matlab繪制曲線圖的相關(guān)資料,需要的朋友可以參考下2021-12-12
Python max內(nèi)置函數(shù)詳細(xì)介紹
這篇文章主要介紹了Python MAX內(nèi)置函數(shù)詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2016-11-11
利用OpenCV+Tensorflow實(shí)現(xiàn)的手勢(shì)識(shí)別
這幾天沒(méi)事,想著再學(xué)點(diǎn)一些視覺(jué)識(shí)別方向的東西,因?yàn)橹白隽蓑?yàn)證碼識(shí)別,有了機(jī)器學(xué)習(xí)的信心,因此這次打算做個(gè)手勢(shì)識(shí)別,下面這篇文章主要給大家介紹了關(guān)于利用OpenCV+Tensorflow實(shí)現(xiàn)的手勢(shì)識(shí)別的相關(guān)資料,需要的朋友可以參考下2022-11-11

