赞
踩
关注
、点赞
、收藏
、订阅。
split方法语法:
str.split(str="", num=string.count(str)).
参数:
返回值:
分割后的字符串列表。
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
-
- text = "小明,去上学。"
-
- text_list = text.split(",")
- for i in text_list:
- print(i)
输出结果:
- 小明
- 去上学。
-
- Process finished with exit code 0
缺点:只能使用单一分隔符进行切分。
re.split()方法语法:
re.split(pattern, string[, maxsplit=0, flags=0])
参数:
pattern | 匹配的正则表达式 |
string | 要匹配的字符串。 |
maxsplit | 分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。 |
flags | 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。 |
返回:
分割后的字符串列表。
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import re
-
- text = "小明,起床。"
-
- text_list = re.split(",", text)
- for i in text_list:
- print(i)
输出结果:
- 小明
- 去上学。
-
- Process finished with exit code 0
若字符串中需要按照多个分隔符进行切分,则可以使用“[]” 的形式,如下:
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import re
-
- text = "小明,起床。吃早饭;然后,去上学"
-
- text_list = re.split("[,。;]", text)
- for i in text_list:
- print(i)
输出结果为:
- 小明
- 起床
- 吃早饭
- 然后
- 去上学
-
- Process finished with exit code 0
也可以使用"|",注意使用 “|”时某些字符需要转义:
text_list = re.split(",|。|;", text)
关注微信公众号【有梦想的程序星空】,了解软件系统和人工智能算法领域的前沿知识,让我们一起学习、一起进步吧!
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。