欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python?字符串使用多個(gè)分隔符分割成列表的2種方法

 更新時(shí)間:2023年04月03日 09:52:03   作者:Looooking  
本文主要介紹了Python?字符串使用多個(gè)分隔符分割成列表,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Python 的字符串默認(rèn)是有一個(gè) split 來把字符串分割成列表的:

>>> test_str = "hello world,nice to meet you"
>>> test_str.split(',')
['hello world', 'nice to meet you']
>>> test_str.split(' ')
['hello', 'world,nice', 'to', 'meet', 'you']

如果我想讓上面的字符串同時(shí)按照逗號和空格分割成下面的列表應(yīng)該怎么做呢?

['hello', 'world', 'nice', 'to', 'meet', 'you']

這個(gè)時(shí)候,re 的 split 就能派上用場了,它可以把正則匹配到的 pattern 都作為分隔符。

>>> import re
>>> test_str = "hello world,nice to meet you"
>>> re.split('[,| ]', test_str)
['hello', 'world', 'nice', 'to', 'meet', 'you']
>>> re.split('[, ]', test_str)
['hello', 'world', 'nice', 'to', 'meet', 'you']
>>> re.split(',| ', test_str)
['hello', 'world', 'nice', 'to', 'meet', 'you']

其實(shí),像 re.sub 和 字符串的 str.replace 也有異曲同工之妙,re.sub 可以同時(shí)替換多個(gè)滿足正則匹配的部分,而不僅僅是某個(gè)固定的字符串。

補(bǔ):partition 系列

partition 系列方法包括 partition () 和 rpartition () 。
partition () 根據(jù)指定的分隔符 (sep) 將字符串進(jìn)行分割,從字符串左邊開始索引分隔符 sep, 索引到則停止索 引,返回的是一個(gè)包含三個(gè)元素的元組 (tuple) ,即 (head, sep, tail) 。

# 遇到第一個(gè)分隔符后就停止索引
print(Str.partition('e'))
# 沒有遇到分隔符 , 返回原字符串和兩個(gè)空字符串
print(Str.partition('f'))
 
# 遇 到 第 一 個(gè) 分 隔 符 后 就 停 止 索 引
print(Str.rpartition('e'))
# 沒 有 遇 到 分 隔 符 , 返 回 兩 個(gè) 空 字 符 串 和 原 字 符 串
print(Str.rpartition('f'))

rpartition () 的功能與 partition () 類似,只不過是從字符串最后面開始分割。

split 和 partition 系列方法的區(qū)別

方法

返回類型是否包含分隔符
split 系列方法list(列表)
partition 系列方法tuple(元組)

到此這篇關(guān)于Python 字符串使用多個(gè)分隔符分割成列表的文章就介紹到這了,更多相關(guān)Python  字符串分隔符分割成列表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論