给定一个函数返回的多字符串,我正在使用以下形式的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'),但这不起作用。
答案 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']