【问题标题】:How do i remove the special chars that show as `\uxxx` in python3 string object?如何删除在 python3 字符串对象中显示为 `\uxxx` 的特殊字符?
【发布时间】:2021-05-05 17:43:07
【问题描述】:

python 字符串对象如下:

The site of the old observatory in Bern \u200bis the point of origin of the CH1903 coordinate system at 46°57′08.66″N 7°26′22.50″E\ufeff / \ufeff46.9524056°N 7.4395833°E\ufeff / 46.9524056; 7.4395833.

我想删除这些显示为原始 unicode 的字符 \u200b \ufeff

【问题讨论】:

    标签: python-3.x regex python-unicode


    【解决方案1】:

    将其编码为ascii 并忽略错误

    >>> s = 'The site of the old observatory in Bern \u200bis the point of origin of the CH1903 coordinate system at 46°57′08.66″N 7°26′22.50″E\ufeff / \ufeff46.9524056°N 7.4395833°E\ufeff / 46.9524056; 7.4395833'
    >>> s.encode('ascii', 'ignore')
    b'The site of the old observatory in Bern is the point of origin of the CH1903 coordinate system at 465708.66N 72622.50E / 46.9524056N 7.4395833E / 46.9524056; 7.4395833'
    

    要将 unicode 字符替换为空格以保持长度不变,可以使用

    #length of original string
    
    >>> s = 'The site of the old observatory in Bern \u200bis the point of origin of the CH1903 coordinate system at 46°57′08.66″N 7°26′22.50″E\ufeff / \ufeff46.9524056°N 7.4395833°E\ufeff / 46.9524056; 7.4395833'
    >>> len(s)
    179
    
    #to maintain the same length
    
    >>> new_s = s.encode('ascii',errors='ignore').decode('utf-8')
    >>> final_s = new_s + ' ' * (len(s) - len(new_s))
    >>> final_s
    'The site of the old observatory in Bern is the point of origin of the CH1903 coordinate system at 465708.66N 72622.50E / 46.9524056N 7.4395833E / 46.9524056; 7.4395833            '
    >>> len(final_s)
    179
    

    这最后会增加额外的空间来保持长度

    【讨论】:

    • 这个很好用,谢谢你的帮助!如果我能得到这些特殊字符在字符串中的位置,我该怎么做?
    • 换句话说,我想用空格替换这些字符以保持字符串长度相同
    • @merlin 我已经更新了我的答案,以保持你可以在答案中做这样的事情的长度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2016-01-23
    • 1970-01-01
    相关资源
    最近更新 更多