在 python 中为所有空白字符进行 TRIM

我正在寻找类似TRIM()python 的东西,但.strip()没有做到这一点。下面是一个例子:


>>> s.strip()

'Elvis Presley made his film debut in this tale of three brothers who, 

 while serving in the Confederate Army, steal a Union Army payroll. \xc2\xa0'


>>> s2.strip()

'Elvis Presley made his film debut in this tale of three brothers who, 

 while serving in the Confederate Army, steal a Union Army payroll.'


>>> s.strip()==s2.strip()

False

我将如何完成上述任务——修剪文本边缘的所有空白字符——我可以在哪里得到s.trim() == s2.trim()(除了做一个 hackish s.strip('\xc2\xa0').strip()?


aluckdog
浏览 105回答 2
2回答

桃花长相依

由于您使用的是 Python 2.7,首先将您的字符串转换为 unicode,然后剥离:s = unicode('test \xc2\xa0', "UTF-8")s.strip()产量:u'test'这将导致 Python 将 识别\xc2\xa0为 Unicode 不间断空格字符,并正确修剪它。没有它,Python 会假定它是一个 ASCII 字符串,并且在该字符集中\xc2,\xa0而不是空格。

暮色呼如

我建议您使用该replace功能。你可以这样做:s1 = s1.replace('\xc2', '').replace('\xa0', '')如果您要修剪大量可能的字符,则可以封装此逻辑:def replace_many(base_string, *to_remove):    result = base_string    for r in to_remove:        result = result.replace(r, '')    return resultreplace_many(s, '\xc2', '\xa0') == s2.strip()>>> True您还可以使用reduce以下方法实现:# In Python 2result = reduce(lambda a, r: a.replace(r, ''), ['\xc2', '\xa0'],     initializer = base_string.strip())# In Python 3import functoolsresult = functools.reduce(lambda a, r: a.replace(r, ''), ['\xc2', 'xa0'],     base_string.strip())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python