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

本文详细介绍了Python中str.split()方法的使用方法及其参数的作用。包括如何通过指定分隔符和最大分隔次数来实现字符串的分割,并给出了具体的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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组成的列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值