16

我对如何使用拆分功能有疑问。

str = 'James;Joseph;Arun;'
str.split(';')

我得到了结果['James', 'Joseph', 'Arun', '']

我需要输出为['James', 'Joseph', 'Arun']

最好的方法是什么?

4

2 回答 2

27

要删除所有空字符串,您可以使用列表推导:

>>> [x for x in my_str.split(';') if x]

或者过滤器/布尔技巧:

>>> filter(bool, my_str.split(';'))

请注意,这还将删除列表开头或中间的空字符串,而不仅仅是结尾。

如果您只想删除最后的空字符串,您可以rstrip在拆分之前使用。

>>> my_str.rstrip(';').split(';')
于 2012-05-28T06:47:46.250 回答
18

First remove ; from the right edge of the string:

s.rstrip(';').split(';')

You can also use filter() (which will filter off also empty elements that weren't found at the end of the string). But the above is really the cleanest approach in my opinion, when you want to avoid empty element at the end, resulting from ";" characters occuring at the end of the string.

EDIT: Actually more accurate than the above (where the above is still more accurate than using filter()) is the following approach:

(s[:-1] if s.endswith(';') else s).split(';')

This will remove only the last element, and only if it would be created empty.

Testing all three solutions you will see, that they give different results:

>>> def test_solution(solution):
    cases = [
        'James;Joseph;Arun;',
        'James;;Arun',
        'James;Joseph;Arun',
        ';James;Joseph;Arun',
        'James;Joseph;;;',
        ';;;',
        ]
    for case in cases:
        print '%r => %r' % (case, solution(case))

>>> test_solution(lambda s: s.split(';'))  # original solution
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun', '']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph', '', '', '']
';;;' => ['', '', '', '']
>>> test_solution(lambda s: filter(bool, s.split(';')))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph']
';;;' => []
>>> test_solution(lambda s: s.rstrip(';').split(';'))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph']
';;;' => ['']
>>> test_solution(lambda s: (s[:-1] if s.endswith(';') else s).split(';'))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph', '', '']
';;;' => ['', '', '']
于 2012-05-28T06:48:51.397 回答