python3.6 split用法_Python3:string中的split()函数

Python3:string中的split()函数

转载请注明作者和出处:http://blog.csdn.net/u011475210操作系统:WINDOWS 10软件版本:python-3.6.2-amd64编  者:WordZzzz

Python3string中的split函数

Python2x中split函数Python3x中split函数样例

Python2.x中split()函数:

老规矩,help!

>>> help(str.split)

Help on method_descriptor:

split(...)

S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the

delimiter string.  If maxsplit is given, at most maxsplit

splits are done. If sep is not specified or is None, any

whitespace string is a separator and empty strings are removed

from the result.

可以看出,在Python2.x中,split()返回的是字符串列表。

Python3.x中split()函数:

同样,help!

>>> help(str.split)

Help on method_descriptor:

split(...)

S.split(sep=None, maxsplit=-1) -> list of strings

Return a list of the words in S, using sep as the

delimiter string.  If maxsplit is given, at most maxsplit

splits are done. If sep is not specified or is None, any

whitespace string is a separator and empty strings are

removed from the result.

啊哦,在Python3.x中,split()返回的也是字符串列表。

样例:

>>> str = "this is string example....wow!!!"

>>> print (str.split( ))

['this', 'is', 'string', 'example....wow!!!']

>>> print (str.split('i',1))

['th', 's is string example....wow!!!']

>>> print (str.split('w'))

['this is string example....', 'o', '!!!']

加入正则表达式:

>>> mySent='This book is the best book on Python or M.L. I have ever laid eyes upon'

>>> mySent.split()                                      #不带参数切分

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'Python', 'or', 'M.L.', 'I', 'have', 'ever', 'laid', 'eyes', 'upon']

>>> import re

>>> regEx = re.compile('\\W')                               #正则表达式,定义分隔符是除单词、数字外的任意字符串

>>> listOfTokens = regEx.split(mySent)                      #根据正则表达式的规则进行切分

>>> listOfTokens

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'Python', 'or', 'M', 'L', '', 'I', 'have', 'ever', 'laid', 'eyes', 'upon']

>>> [tok for tok in listOfTokens if len(tok) > 0]           #去掉空格

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'Python', 'or', 'M', 'L', 'I', 'have', 'ever', 'laid', 'eyes', 'upon']

>>> [tok.lower() for tok in listOfTokens if len(tok) > 2]   #全部小写,去掉长度小于3的单词

['this', 'book', 'the', 'best', 'book', 'python', 'have', 'ever', 'laid', 'eyes', 'upon']

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值