为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

aluckdog 2021-06-08 17:38:46
我正在寻找类似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()?
查看完整描述

2 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

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


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

s.strip()

产量:


u'test'

这将导致 Python 将 识别\xc2\xa0为 Unicode 不间断空格字符,并正确修剪它。


没有它,Python 会假定它是一个 ASCII 字符串,并且在该字符集中\xc2,\xa0而不是空格。


查看完整回答
反对 回复 2021-06-22
?
暮色呼如

TA贡献1853条经验 获得超9个赞

我建议您使用该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 result


replace_many(s, '\xc2', '\xa0') == s2.strip()

>>> True

您还可以使用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())


查看完整回答
反对 回复 2021-06-22
  • 2 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号