如何用python替换字符串中的unicode字符?

Rol*_*ndo 41 python

我有一个字符串,我通过阅读带有子弹的页面的URL来获得,因为项目符号列表具有"•"符号.请注意,文本是来自使用Python 2.7的urllib2.read(webaddress)的Web地址的html源代码.

我知道U + 2022的unicode字符,但是我如何将unicode字符替换成类似的东西呢?

我试过做str.replace("•","某事");

但它似乎不起作用......我该怎么做?

Fre*_*Foo 69

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

    str.decode("utf-8")
    
    Run Code Online (Sandbox Code Playgroud)
  2. 调用replace方法并确保将Unicode字符串作为其第一个参数传递给它:

    str.decode("utf-8").replace(u"\u2022", "*")
    
    Run Code Online (Sandbox Code Playgroud)
  3. 如果需要,编码回UTF-8:

    str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
    
    Run Code Online (Sandbox Code Playgroud)

(幸运的是,Python 3阻止了这个混乱.第3步应该只在I/O之前执行.另外,请注意,调用字符串会str影响内置类型str.)

  • 您能否详细说明“Python 3 制止了这种混乱”的方式?那么我将如何在 Python 3 中做到这一点? (5认同)
  • 我得到: `.decode("utf-8")` -> `AttributeError: 'str' 对象没有属性 'decode'。您的意思是:“编码”吗?` (2认同)

RPa*_*dox 9

将字符串编码为unicode.

>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
Run Code Online (Sandbox Code Playgroud)


小智 8

试试这个。

\n

你会得到一个普通字符串的输出

\n
str.encode().decode('unicode-escape')\n
Run Code Online (Sandbox Code Playgroud)\n

之后,您可以执行任何替换。

\n
str.replace('\xe2\x80\xa2','something')\n
Run Code Online (Sandbox Code Playgroud)\n