在python里学习过使用str.split()来分割字符串,str.split不支持正则及多个切割符号,不感知空格的数量,比如用空格切割,会出现下面情况:
>>> s1="aa bb cc"
>>> s1.split(' ')
['aa', 'bb', '', 'cc']
这时,你也许会想到需要使用正则表达式的来进行查找和分割了,把代码写成这样:
结果输出如下:
0 'Paragraph one\non two lines.'
1 'Paragraph two.'
但是在这个例子里,发现最后一段是不能分割出来,怎么办呢?这时就需要使用re.split()来代替re.findall(),再来看例子:
结果输出如下:
With findall:
0 ('Paragraph one\non two lines.', '\n\n')
1 ('Paragraph two.', '\n\n\n')
2 ('Paragraph three.', '')
With split:
0 'Paragraph one\non two lines.'
1 'Paragraph two.'
2 'Paragraph three.'
深入浅出Numpy
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
>>> s1="aa bb cc"
>>> s1.split(' ')
['aa', 'bb', '', 'cc']
这时,你也许会想到需要使用正则表达式的来进行查找和分割了,把代码写成这样:
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
text = '''Paragraph one
on two lines.
Paragraph two.
Paragraph three.'''
for num, para in enumerate(re.findall(r'(.+?)\n{2,}',
text,
flags=re.DOTALL)
):
print(num, repr(para))
print()
结果输出如下:
0 'Paragraph one\non two lines.'
1 'Paragraph two.'
但是在这个例子里,发现最后一段是不能分割出来,怎么办呢?这时就需要使用re.split()来代替re.findall(),再来看例子:
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
text = '''Paragraph one
on two lines.
Paragraph two.
Paragraph three.'''
print('With findall:')
for num, para in enumerate(re.findall(r'(.+?)(\n{2,}|$)',
text,
flags=re.DOTALL)):
print(num, repr(para))
print()
print()
print('With split:')
for num, para in enumerate(re.split(r'\n{2,}', text)):
print(num, repr(para))
print()
结果输出如下:
With findall:
0 ('Paragraph one\non two lines.', '\n\n')
1 ('Paragraph two.', '\n\n\n')
2 ('Paragraph three.', '')
With split:
0 'Paragraph one\non two lines.'
1 'Paragraph two.'
2 'Paragraph three.'
在这里发现split函数的正则表达式比findall函数的简单很多。