字符串方法0x07 -- 連接/分拆/拆解

轉(zhuǎn)載須注明出處:簡書@Orca_J35 | GitHub@orca-j35

字符串不僅支持所有通用序列操作蟹瘾,還實現(xiàn)了很多附件方法弛秋。
我會以『字符串方法』為標題,分幾篇筆記逐一介紹這些方法尾序。
我會在這倉庫中持續(xù)更新筆記:https://github.com/orca-j35/python_notes

join

?? str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

# 將iterable中字符串進行連接亥啦,并以調(diào)用該方法的字符串作為分隔符
>>> '-'.join(['ab','cd','ef'])
'ab-cd-ef'
>>> '-'.join(['ab'])
'ab'
>>> '-'.join([])
''
>>> '/'.join(dict(name='joy',age=3))
'name/age'
# 如果iterable中包含非字符串對象,則會拋出TypeError異常
# bytes對象同樣會引發(fā)TypeError異常

partition&rpartition

?? str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

# 該方法會將字符分拆為三個部分
# 從字符串低位索引開始辉阶,在一次遇到sep時對字符串進行分拆先壕,會將字符串分拆為3個字符串:
# sep之前的字符構成第一個字符串,sep構成第二個字符串谆甜,sep之后的字符構成第三個字符串
>>> 'abcdabcd'.partition('cd')
('ab', 'cd', 'abcd')
>>> 'abcdabcd'.partition('ab')
('', 'ab', 'cdabcd')
>>> 'abcd'.partition('cd')
('ab', 'cd', '')
# 如果字符串中沒有sep垃僚,也會返回三個元組:
# 原字符串構成第一個字符串,后兩個字符串均為空
>>> 'abcdabcd'.partition('ef')
('abcdabcd', '', '')

?? str.rpartition(sep)

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

# 該方法會將字符分拆為三個部分
# 從字符串高位索引開始规辱,在一次遇到sep時對字符串進行分拆谆棺,會將字符串分拆為3個字符串:
# sep之前的字符構成第一個字符串,sep構成第二個字符串按摘,sep之后的字符構成第三個字符串
>>> 'abcdabcd'.rpartition('cd')
('abcdab', 'cd', '')
>>> 'abcdabcd'.rpartition('ab')
('abcd', 'ab', 'cd')
>>> 'abcd'.rpartition('ab')
('', 'ab', 'cd')
# 如果字符串中沒有sep包券,也會返回三個元組:
# 前兩個字符串均為空纫谅,原字符串構成第三個字符串,
>>> 'abcdabcd'.rpartition('ef')
('', '', 'abcdabcd')

split&rsplit

?? str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The separgument may consist of multiple characters (for example, '1<>2<>3'.split('<>')returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

# 該方法會以sep作為分隔符溅固,對字符串進行拆解付秕,并返回拆解后的列表
# 拆解操作始于字符的左側(cè)
>>> '1,2,3'.split(',')
['1', '2', '3']
# maxsplit用于指定分解次數(shù);默認值是-1侍郭,表示進行最大限度的拆解
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> ''.split('-')
['']
>>> 'bcd'.split('a')
['bcd']
# 連續(xù)的分隔符和尾部的分隔符询吴,均會產(chǎn)生空字符串
>>> '1,2,,,3,'.split(',')
['1', '2', '', '', '3', '']
# sep可以包含多個字符
>>> '1<>2<>3'.split('<>')
['1', '2', '3']

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

# 如果sep的值為None,則會將連續(xù)的空白符視為分隔符
>>> '1 2 3'.split()
['1', '2', '3']
>>> '1\t2\n3'.split()
['1', '2', '3']
>>> '1,2,3'.split()
['1,2,3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
# 字符串的頭部和尾部的空白符亮元,不會產(chǎn)生空字符串
>>> '   1   2   3   '.split()
['1', '2', '3']
# 拆解僅包含空白符的字符串會返回一個空列表
>>> '  '.split()
[]
>>> ''.split()
[]

?? str.rsplit(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit()behaves like split() which is described in detail below.

# 該方法會以sep作為分隔符猛计,對字符串進行拆解,并返回拆解后的列表
# 拆解操作始于字符的右側(cè)爆捞,其余行為和split()一致
>>> '1,2,3'.rsplit(',', maxsplit=1)
['1,2', '3']
>>> ',1,2,,3,'.rsplit(',')
['', '1', '2', '', '3', '']
>>> '1 2 3'.rsplit(maxsplit=1)
['1 2', '3']

splitlines

?? str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

該方法會將行邊界符作為分拆點奉瘤,將字符串拆解為由多字符串組成的列表。當 keependsTrue· 時煮甥,則會在結(jié)果中保留行邊界符盗温。

以下是作為分拆依據(jù)的行邊界符(line boundaries)。注意成肘,行邊界符是通用換行符('\n','\r\n','\r')的超集(universal newlines)

Representation Description
\n Line Feed
\r Carriage Return
\r\n Carriage Return + Line Feed
\v or \x0b Line Tabulation
\f or \x0c Form Feed
\x1c File Separator
\x1d Group Separator
\x1e Record Separator
\x85 Next Line (C1 Control Code)
\u2028 Line Separator
\u2029 Paragraph Separator

Changed in version 3.2: \v and \f added to list of line boundaries.

# \r\n 被視作一個整體
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

# 在遇到空字符串時卖局,splitlines會返回一個空列表
>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

對比 split('\n') :

# 在給定sep時,split會在遇到空字符串時返回一個包含空字符串的列表
>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末双霍,一起剝皮案震驚了整個濱河市砚偶,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌洒闸,老刑警劉巖染坯,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異顷蟀,居然都是意外死亡酒请,警方通過查閱死者的電腦和手機骡技,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門鸣个,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人布朦,你說我怎么就攤上這事囤萤。” “怎么了是趴?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵涛舍,是天一觀的道長。 經(jīng)常有香客問我唆途,道長富雅,這世上最難降的妖魔是什么掸驱? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮没佑,結(jié)果婚禮上毕贼,老公的妹妹穿的比我還像新娘。我一直安慰自己蛤奢,他們只是感情好鬼癣,可當我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著啤贩,像睡著了一般待秃。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上痹屹,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天章郁,我揣著相機與錄音,去河邊找鬼志衍。 笑死驱犹,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的足画。 我是一名探鬼主播雄驹,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼淹辞!你這毒婦竟也來了医舆?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤象缀,失蹤者是張志新(化名)和其女友劉穎蔬将,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體央星,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡霞怀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了莉给。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片毙石。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖颓遏,靈堂內(nèi)的尸體忽然破棺而出徐矩,到底是詐尸還是另有隱情,我是刑警寧澤叁幢,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布滤灯,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏鳞骤。R本人自食惡果不足惜窒百,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望豫尽。 院中可真熱鬧贝咙,春花似錦、人聲如沸拂募。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽陈症。三九已至蔼水,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間录肯,已是汗流浹背趴腋。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留论咏,地道東北人优炬。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像厅贪,于是被迫代替她去往敵國和親蠢护。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容