【问题标题】:Split function - avoid last empty space拆分功能 - 避免最后一个空白
【发布时间】:2012-05-28 06:45:58
【问题描述】:

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

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

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

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

最好的方法是什么?

【问题讨论】:

  • 请不要使用str作为变量名。它隐藏了内置的str
  • @Mark Byers 感谢您的评论,我的实际 var 名称不同。

标签: python split


【解决方案1】:

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

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

或者过滤器/布尔技巧:

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

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

如果您只想删除末尾的空字符串,可以在拆分前使用rstrip

>>> my_str.rstrip(';').split(';')

【讨论】:

  • +1 直到现在才听说过filer(bool,x),只听说过filter(None,x)。您认为哪个更好?
  • @jamylak:两者都很好。我更喜欢filter(bool, x),因为它更清楚地说明了它的工作原理。使用None 作为过滤功能似乎很神奇(除非您已阅读文档以了解其工作原理)。但其他人更喜欢filter(None, x),所以我想这并没有太大区别。
【解决方案2】:

首先从字符串的右边缘移除;

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

您也可以使用filter()(它也会过滤掉在字符串末尾找不到的空元素)。但在我看来,上面确实是最干净的方法,当你想避免最后出现空元素时,由于字符串末尾出现“;”字符。

编辑:实际上比上面更准确(上面仍然比使用filter()更准确)是以下方法:

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

这将仅删除最后一个元素,并且仅当它被创建为空时。

测试您将看到的所有三种解决方案,它们会给出不同的结果:

>>> 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', '', '']
';;;' => ['', '', '']

【讨论】:

  • IMO 将其更改为 rstrip,因为他说 last 空白。
  • @jamylak:正确,我在您撰写评论时添加了该信息。请查看更新后的答案。
猜你喜欢
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 2019-04-08
相关资源
最近更新 更多