本文实例讲述了Python针对任意多的分隔符拆分字符串操作。分享给大家供大家参考,具体如下:
问题:将分隔符(以及分隔符之间的空格)不一致的字符串拆分为不同的字段;
解决方案:使用更为灵活的re.split()方法,该方法可以为分隔符指定多个模式。
说明:字符串对象的split()只能处理简单的情况,而且不支持多个分隔符,对分隔符周围可能存在的空格也无能为力。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# example.py
#
# Example of splitting a string on multiple delimiters using a regex
import re #导入正则表达式模块
line = 'asdf fjdk; afed, fjek,asdf, foo'
# (a) Splitting on space, comma, and semicolon
parts = re.split(r '[;,\s]\s*' , line)
print (parts)
# (b) 正则表达式模式中使用“捕获组”,需注意捕获组是否包含在括号中,使用捕获组导致匹配的文本也包含在最终结果中
fields = re.split(r '(;|,|\s)\s*' , line)
print (fields)
# (c) 根据上文的分隔字符改进字符串的输出
values = fields[:: 2 ]
delimiters = fields[ 1 :: 2 ]
delimiters.append('')
print ( 'value =' , values)
print ( 'delimiters =' , delimiters)
newline = ''.join(v + d for v,d in zip (values, delimiters))
print ( 'newline =' , newline)
# (d) 使用非捕获组(?:...)的形式实现用括号对正则表达式模式分组,且不输出分隔符
parts = re.split(r '(?:,|;|\s)\s*' , line)
print (parts)
|
1
2
3
4
5
6
7
8
9
|
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = RESTART = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
>>>
[ 'asdf' , 'fjdk' , 'afed' , 'fjek' , 'asdf' , 'foo' ]
[ 'asdf' , ' ' , 'fjdk' , ';' , 'afed' , ',' , 'fjek' , ',' , 'asdf' , ',' , 'foo' ]
value = [ 'asdf' , 'fjdk' , 'afed' , 'fjek' , 'asdf' , 'foo' ]
delimiters = [ ' ' , ';' , ',' , ',' , ',' , '']
newline = asdf fjdk;afed,fjek,asdf,foo
[ 'asdf' , 'fjdk' , 'afed' , 'fjek' , 'asdf' , 'foo' ]
>>>
|
(代码摘自《Python Cookbook》)
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://www.cnblogs.com/apple2016/p/5767294.html