如何删除Unicode字符串中的空白

2024-07-04 08:00:37 发布

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

我是python新手,正在尝试做一些web抓取。 我得到的字符串是:u' Kathy and Othon Prounis ' 我想要的最终输出是u'Kathy and Othon Prounis',其中多余的空格被删除。 我试过:

temp = re.split(' ',u' Kathy  and Othon Prounis ')

给予

[u'', u'Kathy', u'', u'and', u'Othon', u'Prounis', u'']

但是我不能在上面做temp.remove(u'')。你知道吗


Tags: and字符串rewebtempremovesplit空格
1条回答
网友
1楼 · 发布于 2024-07-04 08:00:37

您需要确保在字符串的开始/结束处不会发生拆分。您可以使用regex lookarounds执行此操作:

>>> re.split('(?<!^) +(?!$)',u' Kathy  and Othon Prounis ')
[' Kathy', 'and', 'Othon', 'Prounis ']

或者,对regex的一个主要简化意味着在调用前剥离文本,所以如果可以的话,应该这样做。你知道吗

>>> re.split(' +', ' Kathy  and Othon Prounis '.strip())
['Kathy', 'and', 'Othon', 'Prounis']

为此,为什么不直接做呢

>>> ' Kathy  and Othon Prounis '.split()
['Kathy', 'and', 'Othon', 'Prounis']

什么?你知道吗

相关问题 更多 >

    热门问题