在 n 个或更多空格处拆分字符串

Split string on n or more whitespaces

我有一个这样的字符串:

sentence = 'This is   a  nice    day'

我想要以下输出:

output = ['This is', 'a  nice',  'day']

在这种情况下,我将字符串拆分为 n=3 个或更多空格,这就是为什么它像上面所示那样拆分的原因。

我怎样才能有效地为任何 n 执行此操作?

您可以尝试使用 Python 的正则表达式拆分:

sentence = 'This is   a  nice day'
output = re.split(r'\s{3,}', sentence)
print(output)

['This is', 'a  nice day']

要处理实际变量 n,我们可以尝试:

n = 3
pattern = r'\s{' + str(n) + ',}'
output = re.split(pattern, sentence)
print(output)

['This is', 'a  nice day']

您可以使用基本的 .split() 函数:

sentence = 'This is   a  nice day'
n = 3
sentence.split(' '*n)

>>> ['This is', 'a  nice day']

您还可以按 n 个空格拆分,剥离结果并删除空元素(如果有几个这样的长空格会产生它们):

sentence = 'This is   a  nice day'
n = 3
parts = [part.strip() for part in sentence.split(' ' * n) if part.strip()]
x = 'This is   a  nice day'    
result = [i.strip() for i in x.split(' ' * 3)]
print(result)

['This is', 'a  nice day']