python - 如何去除unicode字符串中的空格

标签 python regex string

我是 python 新手,正在尝试进行一些网络抓取。 我得到的字符串是: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'')

最佳答案

您需要确保在字符串的开头/结尾处不会发生拆分。您可以使用正则表达式环视来做到这一点:

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

或者,对正则表达式的重大简化意味着在调用之前删除您的文本,因此如果可以选择,您应该这样做。

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

为此,为什么不这样做

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

关于python - 如何去除unicode字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525569/

相关文章:

python - 计算矩阵在所有对角线上的迹

python - 为什么我们不能 **unsplat 'self' 到一个方法中?

java - 获取单引号或空格之间的字符串

java replaceAll 不适用于\n 字符

java - android java - 将字符串转换为字节变量

python - 多个for循环,不满足条件只打印一次else

python - 如何将文本文件加载到 pandas 数据框中?

regex - 特定正则表达式的帮助 - 不包含某些字符串

regex - 使用正则表达式匹配1到105之间的数字

string - 使用空接口(interface)更改函数中的 arg