我是 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/