【看這個就夠了】Python中split()方法深度解析(看完這個你再不會算我輸)

1 定義

1.1 描述

Python中split() 方法通過指定分隔符對字符串進行切片並返回一個列表。

1.2 語法格式

string.split(str="", num=string.count(str))

參數說明:
1. str: 分隔符,默認爲所有的空字符,
包括 空格、換行(\n)、水平製表符(\t)、 垂直製表符(\v)、 換頁(\f)、回車(\r);(python中轉義字符表看附)
2. num: 分割次數。默認爲 -1, 即分隔所有。

如果參數 num 有指定值,則分隔 num+1 個子字符串

2 實戰

2.1 參數爲空情況

分隔符str 默認爲所有的空字符,包括 空格、換行(\n)、水平製表符(\t)、 垂直製表符(\v)、 換頁(\f)、回車(\r)。
(有些同志博客只提到了空格、換行\t、製表\t、實則還包括\v \f \r)

string = 'abcd efg\nopq\trst\vuvw  x\fyz'
print(string)
print('======切分後=========')
stringlist = string.split()
print(stringlist)

# 輸出結果
abcd efg
opq	rstuvw  xyz
======切分後=========
['abcd', 'efg', 'opq', 'rst', 'uvw', 'x', 'yz']

2.2 單個分隔符情況

2.2.1 以空格作爲分隔符

string = 'hello world,\nhello python.'
print(string)
print('======切分後=========')
print(string.split(" "))

# 輸出結果
hello world,
hello python.
======切分後=========
['hello', 'world,\nhello', 'python.']

注意:str分隔符必須爲字符
錯誤示例:

string = 'python2 and python 3.'
print(string.split(2))

# 輸出結果
TypeError: must be str or None, not int

正確示例:

string = 'python2 and python 3.'
print(string.split('2'))

# 輸出結果
['python', ' and python 3.']

2.2.2 以其他字符作爲分隔符

string = 'hello world,\nhello python.'
print(string.split('o'))

# 輸出結果
['hell', ' w', 'rld,\nhell', ' pyth', 'n.']

2.2.3 字符串首尾出現分隔符

當字符串收尾存在分隔符的時候,有多少個分隔符就產生多少個空字符。(不傳參情況除外)

string = 'ppphello worldppp,hello pp python.pp'
print(string.split('p'))

# 輸出結果
['', '', '', 'hello world', '', '', ',hello ', '', ' ', 'ython.', '', '']

2.2.4 字符串中間出現分隔符

注意:如果是單個出現,就和普通的分割一樣;
如果是多個出現,則兩個分隔符之間會產生一個空字符

string = 'ppphello worldppp,hello pp python.pp'
print(string.split('p'))

# 輸出結果
['', '', '', 'hello world', '', '', ',hello ', '', ' ', 'ython.', '', '']

# 所以這裏world後的3個p,產生兩個空字符,hello 後面2個p會產生一個空字符。
#再後面的一個是空格字符,不是空字符。

2.2.5 指定分割次數

參數num,分割次數。指定num後,則共有 num+1 個子字符串

string = 'hello world,hello python.'
print(string.split('o', 2))

# 輸出結果
['hell', ' w', 'rld,hello python.']

2.3 多個分隔符情況

注意:
Python中split()方法只支持單個分隔符;
re模塊的split()函數支持多個分隔符對字符串進行分割,其中不同的分隔符用 “|” 隔開。

2.3.1 多個分隔符例子

import re
string = 'hello world,\nhello python.'
stringlist = re.split(r'e|o|\n',string)
print(stringlist)

# 輸出結果
['h', 'll', ' w', 'rld,', 'h', 'll', ' pyth', 'n.']

2.3.2 首尾、中間出現分隔符

與python中split()方法一樣的處理。
參考
2.2.3 字符串首尾出現分隔符
2.2.4 字符串中間出現分隔符

import re
string = 'rrhelloooworldee'
stringlist = re.split(r'e|o',string)
print(stringlist)
# 輸出結果
['rrh', 'll', '', '', 'w', 'rld', '', '']

3 附錄

Python中的常用轉義字符
在這裏插入圖片描述

如文章對您有幫助,感謝您的點贊+關注(^ _ ^)

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