separator 是分隔符字符串
如果指定了maxsplit,則最多完成maxsplit分割(因此,列表最多包含maxsplit + 1個元素)
如果沒有指定maxsplit或-1,那麼拆分的數量就沒有限制(所有可能的拆分都進行了)。
如果separator指定,則連續的分隔符不會分組在一起,並被視為定界空字符串(例如,'1,,2'.split(',') 返回 ['1', '', '2'])
如果separator未指定或為None,則連續的空白行將被視為單個分隔符,並且如果字符串具有前導或尾隨空格,則結果在開頭或結尾將不包含空字符串。例如,' 1 2 3 '.split()返回['1', '2', '3']
示例1:使用空格分割字符串
在這個示例腳本中,我們將使用空格作為分隔符將包含字符串的句子分割成多個子字符串。如果沒有要定義的分隔符,那麼可以只提供split(),它在默認情況下將分隔符視為None。
#!/usr/bin/env python3
mystring = "This is Python Tutorial linuxmi"
print(type(mystring)) ## This will return type as string
newstring = mystring.split() ## split the string and store into newstring var
print(newstring) ## print the content of newstring
print(type(newstring)) ## the new type would be list after splitting
該腳本的輸出:
<class 'str'>
['This', 'is', 'Python', 'Tutorial', 'linuxmi']
<class 'list'>
string.split()將在傳遞的參數上拆分和分割字符串,並返回列表中的所有部分。該列表將不包括分割字符。
示例2:使用逗號作為分隔符
在這個例子中,我們將定義一個分隔符逗號( , ),並將字符串分割成列表
#!/usr/bin/env python3
mystring = "abc,def,linuxmi"
print(type(mystring)) ## This will return type as string
newstring = mystring.split(',') ## split the string using ',' and store into newstring var
print(newstring) ## print the content of newstring
print(type(newstring)) ## the new type would be list after splitting
#!/usr/bin/env python3
mystring = "abc,def,ghi,tre,linuxmi.com"
print(type(mystring)) ## This will return type as string
## split the string using sep=',' with maxlimit=1 and store into newstring var
newstring = mystring.split(',',1)
print(newstring) ## print the content of newstring
print(type(newstring)) ## the new type would be list after splitting
#!/usr/bin/env python3
filename = '/usr/share/doc/grep/README'
try:
with open(filename, encoding='utf-8') as f:
contents= f.read()
except FileNotFoundError:
print(f'Sorry, the file {filename} does not exits')
else:
words = contents.split()
num_words = len(words)
print(f'The file {filename} has about {num_words} words.')
#!/usr/bin/env python3
mystring = 'linuxmi.com we are testing python split strin'
## One-Liner
w = [[x for x in line.split() if len(x)>5] for line in mystring.split('\n')]
## Result
print(w)
...END...
長按或掃描下面的二維碼關注Linux公社
關注Linux公社,添加「星標」
每天獲取技術乾貨,讓我們一起成長
合作聯繫微信:linuxgs