我有一个字符串,我通过阅读带有子弹的页面的URL来获得,因为项目符号列表具有"•"符号.请注意,文本是来自使用Python 2.7的urllib2.read(webaddress)的Web地址的html源代码.
我知道U + 2022的unicode字符,但是我如何将unicode字符替换成类似的东西呢?
我试过做str.replace("•","某事");
但它似乎不起作用......我该怎么做?
Fre*_*Foo 69
将字符串解码为Unicode.假设它是UTF-8编码的:
str.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)调用replace
方法并确保将Unicode字符串作为其第一个参数传递给它:
str.decode("utf-8").replace(u"\u2022", "*")
Run Code Online (Sandbox Code Playgroud)如果需要,编码回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
.)
将字符串编码为unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
Run Code Online (Sandbox Code Playgroud)
小智 8
试试这个。
\n你会得到一个普通字符串的输出
\nstr.encode().decode('unicode-escape')\n
Run Code Online (Sandbox Code Playgroud)\n之后,您可以执行任何替换。
\nstr.replace('\xe2\x80\xa2','something')\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
92802 次 |
最近记录: |