【问题标题】:List comprehension space removal in pythonpython中的列表理解空间删除
【发布时间】:2018-10-26 14:05:00
【问题描述】:

我仍然对 python 中的列表理解有所了解,但我相信这是我完成这项任务所需要的。

我有一个已转换为列表的字符串。如果两个相邻元素都是小写字母字符,我想删除空格。

例如

 INPUT> Bartho lemew The Rhinoceros
 OUTPUT> Bartholemew The Rhinoceros

【问题讨论】:

  • 您可以在字符串上的空格上进行拆分,这会将您的句子放入一个没有任何空格的列表中
  • 不要尝试通过列表理解来执行此操作。
  • 输出中的'u' 来自哪里?

标签: python string list list-comprehension


【解决方案1】:

我认为re.sub 更适合这里:

import re

def remove_spaces(string):
    return re.sub(r'(?<=[a-z]) (?=[a-z])', '', string)

print(remove_spaces('Bartho lemew The Rhinoceros'))
# Bartholemew The Rhinoceros

【讨论】:

    【解决方案2】:

    与另一个答案非常相似

    import re
    a='Bartho lemew The Rhinoceros asdas'
    print(re.sub('([A-Z][a-z]*)(\s)([a-z])(\w*)',r'\1\3\4',a))
    

    【讨论】:

      【解决方案3】:

      我认为对于初学者的问题,stackoverflow 上的正则表达式有点夸大了。对于这个问题,尽管它们绝对是正确的选择。话虽如此,您还要求解决问题的列表理解,我是谁来拒绝您?

      def remove_spaces(s):
          s = s.join(['A', 'A'])
          return ''.join([c for i, c in enumerate(s)
                              if c!=' ' or not (s[i-1]+s[i+1]).islower()][1:-1])
      

      【讨论】:

        猜你喜欢
        • 2021-11-20
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 2017-11-02
        • 2022-01-10
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多