1. 程式人生 > >Python split()的用法以及如何利用空格進行輸入

Python split()的用法以及如何利用空格進行輸入

Python 3.6.4 Document 中關於 str.split() 原內容如下:

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+1 elements). If maxsplit is notspecified 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 aredeemed to delimit empty strings (for example, '1,,2'.split(',') returns['1', '', '2']). The sep argument may consist of multiple characters(for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']).Splitting an empty string with a specified separator returns [''].
If sep is not specified or is None, a different splitting algorithm isapplied: runs of consecutive whitespace are regarded as a single separator,and the result will contain no empty strings at the start or end if thestring has leading or trailing whitespace. Consequently, splitting an emptystring or a string consisting of just whitespace with a None separatorreturns [].str.split(sep=None,maxsplit=-1)maxsplit為分隔數(間隔的數量)
如果maxsplit為-1或者沒有指定數值那麼會按照所有相應的分隔符(sep)進行分隔。如果maxsplit指定了數值,則按照從左到右maxsplit個分隔符(sep)進行分隔。sep為分隔符
如果指定了sep的值(如sep=',' )則按照sep的值進行分隔。如果沒有指定sep的值或者sep=None,那麼預設空格為分隔符且執行完成後字串開頭和結尾不會存在空格。例如:
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
如果想利用空格輸入數字也可以用split()達到目的例如:
num =[int(x) for x in input().split()]
print(num)

input:3 2 8 5
output:[3, 2, 8, 5]
最終得到一個由int組成的列表