【问题标题】:replace or delete specific unicode characters in python替换或删除python中的特定Unicode字符
【发布时间】:2017-03-30 18:49:26
【问题描述】:

似乎有很多关于在其他语言中执行此操作的帖子,但我似乎无法弄清楚在 Python 中如何(我使用的是 2.7)。

明确地说,我希望将字符串保留为 unicode,只是能够替换某些特定字符。

例如:

thisToken = u'tandh\u2013bm'
print(thisToken)

打印中间有 m 破折号的单词。我只想删除 m-dash。 (但使用索引,因为我希望能够在任何找到这些特定字符的地方执行此操作。)

我尝试使用replace,就像你对任何其他角色一样:

newToke = thisToken.replace('\u2013','')
print(newToke)

但它只是不起作用。任何帮助深表感谢。 赛斯

【问题讨论】:

  • 如果你在文件的顶部使用from __future__ import unicode_literals,所有的字符串文字都是自动的unicode,它在这里会有所帮助(但是当一些字符串需要是字节时要小心意外,你可以为它们使用b 前缀)。

标签: python python-2.7 unicode


【解决方案1】:

你可以在这篇文章中看到答案:How to replace unicode characters in string with something else python?

将字符串解码为 Unicode。假设它是 UTF-8 编码的:

str.decode("utf-8")

调用 replace 方法并确保将 Unicode 字符串作为第一个参数传递给它:

str.decode("utf-8").replace(u"\u2022", "")

如果需要,编码回 UTF-8:

str.decode("utf-8").replace(u"\u2022", "").encode("utf-8")

【讨论】:

    【解决方案2】:

    您要搜索替换的字符串也必须是 Unicode 字符串。试试:

    newToke = thisToken.replace(u'\u2013','')
    

    【讨论】:

    • 实际上最好是第二个参数也是u'' :-)
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多