您的位置:首页 > 编程语言 > Python开发

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

2018-02-23 17:04 666 查看
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 [].Python Document原文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组成的列表
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python split() whitespace
相关文章推荐