我在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()
)?在
由于您使用的是Python 2.7,请先将字符串转换为unicode,然后再剥离:
产量:
^{pr2}$这将导致Python将
\xc2\xa0
识别为Unicode非中断空格字符,并对其进行适当的修剪。在没有这个,Python假设它是一个ASCII字符串,并且在这个字符集中}不是空白。在
\xc2
和{我建议您使用
replace
函数。您可以这样做:如果要删除大量可能的字符,可以封装此逻辑:
^{pr2}$您也可以使用
reduce
来实现:相关问题 更多 >
编程相关推荐