python中的列表空间删除

2024-06-07 05:54:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍然在研究python中的列表理解,但我相信这正是我完成这项任务所需要的。你知道吗

我有一个字符串,我已经投到一个列表。如果两个相邻的元素都是小写字母字符,我想去掉空格。你知道吗

例如

 INPUT> Bartho lemew The Rhinoceros
 OUTPUT> Bartholemew The Rhinoceros

Tags: the字符串元素列表inputoutput字符空格
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])

我认为^{}更适合这里:

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

与另一个答案非常相似

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

相关问题 更多 >