如何在python中拆分多字符串?

时间:2011-01-11 05:24:47

标签: python

给定一个函数返回的多字符串,我正在使用以下形式的ctypes访问:

"the quick brown fox\x00jumped over the lazy\00programmer\00\00"

将此转换为这样的python列表的最佳方法是什么:

["the quick brown fox", "jumped over the lazy", "programmer"]

我尝试使用foo.split('\ x00'),但这不起作用。

3 个答案:

答案 0 :(得分:5)

鉴于

sentence = "the quick brown fox\x00jumped over the lazy\00programmer\00\00"
[phrase for phrase in sentence.split("\x00") if phrase != ""]

修改
直接从马的嘴里出来:

>>> sentence = "the quick brown fox\x00jumped over the lazy\00programmer\00\00"
>>> [phrase for phrase in sentence.split('\x00') if phrase != ""]
['the quick brown fox', 'jumped over the lazy', 'programmer']

Python 2.6.1 (r261:67515, Jul  9 2009, 14:20:26) 

答案 1 :(得分:3)

使用过滤器将是解决此问题的一种优雅方式。

>>> s = "the quick brown fox\x00jumped over the lazy\00programmer\00\00"  
>>> filter(None, s.split('\x00'))  
['the quick brown fox', 'jumped over the lazy', 'programmer']

答案 2 :(得分:1)

>>> s = "the quick brown fox\x00jumped over the lazy\00programmer\00\00"
>>> s.strip('\x00').split('\x00')
['the quick brown fox', 'jumped over the lazy', 'programmer']