首页 > 解决方案 > python中的列表理解空间删除

问题描述

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

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

例如

 INPUT> Bartho lemew The Rhinoceros
 OUTPUT> Bartholemew The Rhinoceros

标签: pythonstringlistlist-comprehension

解决方案


我认为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

推荐阅读