![](/img/trans.png)
[英]How to replace invalid unicode characters in a string in Python?
[英]How to replace unicode characters in string with something else python?
由于项目符号列表,我有一个字符串是从阅读带有符号“•”的项目符号的 HTML 网页中获得的。 请注意,该文本是来自使用 Python 2.7 的urllib2.read(webaddress)
的网页的 HTML 源代码。
我知道项目符号字符的 unicode 字符为U+2022
,但是我如何用其他东西实际替换该 unicode 字符?
我试着做str.replace("•", "something")
但它似乎不起作用......我该怎么做?
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)
试试这个。
你会得到一个普通字符串的输出
str.encode().decode('unicode-escape')
之后,您可以执行任何替换。
str.replace('•','something')
str1 = "This is Python\u500cPool"
str.replace("•", "something")
如果要删除所有 \u 字符。 下面的代码给你
def replace_unicode_character(self, content: str):
content = content.encode('utf-8')
if "\\x80" in str(content):
count_unicode = 0
i = 0
while i < len(content):
if "\\x" in str(content[i:i + 1]):
if count_unicode % 3 == 0:
content = content[:i] + b'\x80\x80\x80' + content[i + 3:]
i += 2
count_unicode += 1
i += 1
content = content.replace(b'\x80\x80\x80', b'')
return content.decode('utf-8')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.