gpt4 book ai didi

python - 如何删除列表中的空格?

转载 作者:行者123 更新时间:2023-12-01 23:20:11 24 4
gpt4 key购买 nike

我有一条短信:

text = '''
Wales greatest moment. Lille is so close to the Belgian
border,
this was essentially a home game for one of the tournament favourites. Their
confident supporters mingled with their new Welsh fans on the streets,
buying into the carnival spirit - perhaps more relaxed than some might have
been before a quarter-final because they thought this was their time.
In the driving rain, Wales produced the best performance in their history to
carry the nation into uncharted territory. Nobody could quite believe it.'''

我有一个代码:

 words = text.replace('.',' ').replace(',',' ').replace('\n',' ').split(' ')
print(words)

和输出:

['Wales', 'greatest', 'moment', '', 'Lille', 'is', 'so', 'close', 'to', 'the', 'Belgian', 'border', '', '', 'this', 'was', 'essentially', 'a', 'home', 'game', 'for', 'one', 'of', 'the', 'tournament', 'favourites', '', 'Their', '', 'confident', 'supporters', 'mingled', 'with', 'their', 'new', 'Welsh', 'fans', 'on', 'the', 'streets', '', '', 'buying', 'into', 'the', 'carnival', 'spirit', '-', 'perhaps', 'more', 'relaxed', 'than', 'some', 'might', 'have', '', 'been', 'before', 'a', 'quarter-final', 'because', 'they', 'thought', 'this', 'was', 'their', 'time', '', 'In', 'the', 'driving', 'rain', '', 'Wales', 'produced', 'the', 'best', 'performance', 'in', 'their', 'history', 'to', '', 'carry', 'the', 'nation', 'into', 'uncharted', 'territory', '', 'Nobody', 'could', 'quite', 'believe', 'it', '']

你可以看到,列表有空格,我删除了'\n', ',' and '.'.

但现在我不知道如何删除这些空格。

最佳答案

您可以 filter他们,如果你不喜欢他们

no_empties = list(filter(None, words))

If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

这是有效的,因为空元素被认为是错误的。

关于python - 如何删除列表中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68199088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com