在python中修剪所有空白字符

2024-09-27 07:35:09 发布

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

我在python中寻找类似于TRIM()的东西,但是.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()(而不仅仅是做一个粗俗的s.strip('\xc2\xa0').strip())?在


Tags: ofinthisthreestripfilms2made
2条回答

由于您使用的是Python 2.7,请先将字符串转换为unicode,然后再剥离:

s = unicode('test \xc2\xa0', "UTF-8")
s.strip()

产量:

^{pr2}$

这将导致Python将\xc2\xa0识别为Unicode非中断空格字符,并对其进行适当的修剪。在

没有这个,Python假设它是一个ASCII字符串,并且在这个字符集中\xc2和{}不是空白。在

我建议您使用replace函数。您可以这样做:

s1 = s1.replace('\xc2', '').replace('\xa0', '')

如果要删除大量可能的字符,可以封装此逻辑:

^{pr2}$

您也可以使用reduce来实现:

# In Python 2
result = reduce(lambda a, r: a.replace(r, ''), ['\xc2', '\xa0'], 
    initializer = base_string.strip())

# In Python 3
import functools
result = functools.reduce(lambda a, r: a.replace(r, ''), ['\xc2', 'xa0'], 
    base_string.strip())

相关问题 更多 >

    热门问题