【问题标题】:Remove \u from string?从字符串中删除 \u?
【发布时间】:2017-07-09 18:45:38
【问题描述】:

我在列表中有几个字词是'\uword'。我想用空字符串替换'\u'。我环顾四周,但到目前为止没有任何东西对我有用。我尝试使用"%r"%word 转换为原始字符串,但这不起作用。我也尝试使用word.encode('unicode-escape'),但没有得到任何结果。有什么想法吗?

编辑

添加代码

word = '\u2019'
word.encode('unicode-escape')
print(word) # error

word = '\u2019'
word = "%r"%word
print(word) # error

【问题讨论】:

  • 请包含一些代码,显示您已经尝试过的内容。
  • '\uword'.replace(r'\u', '') -> 'word'
  • 用''替换\\u
  • @Petar 添加代码
  • @ClockSlave 是的,你是 100% 正确的。好地方。您应该提交它作为您问题的答案。

标签: python regex python-unicode unicode-escapes


【解决方案1】:

鉴于您只处理字符串。 我们可以使用 string 函数简单地将其转换为字符串。

>>> string = u"your string"
>>> string
u'your string'
>>> str(string)
'your string'

猜猜就可以了!

【讨论】:

    【解决方案2】:

    我在假设字符串的.encode 方法修改字符串就地类似于列表的.sort() 方法时犯了一个错误。但是根据文档

    bytes.decode() 的相反方法是 str.encode(),它返回 Unicode 字符串的字节表示,以请求的编码进行编码。

    def remove_u(word):
        word_u = (word.encode('unicode-escape')).decode("utf-8", "strict")
        if r'\u' in word_u: 
            # print(True)
            return word_u.split('\\u')[1]
        return word
    
    vocabulary_ = [remove_u(each_word) for each_word in vocabulary_]
    

    【讨论】:

      【解决方案3】:

      如果我理解正确,您不必使用正则表达式。试试看:

      >>> # string = '\u2019'
      >>> char = string.decode('unicode-escape')
      >>> print format(ord(char), 'x')
      2019
      

      【讨论】:

        【解决方案4】:

        因为您面临编码和 unicode 的问题,所以了解您正在使用的 python 版本会很有帮助。 我不知道我是否正确,但这应该可以解决问题:

        string = r'\uword'
        string.replace(r'\u','')
        

        【讨论】:

        • 我没有原始字符串。我有一个'\u2019' 形式的字符串文字。当string = '\u2019' 时上述方法不起作用
        猜你喜欢
        • 1970-01-01
        • 2013-10-31
        • 2017-02-20
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 2017-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多