Python - 替换字符串中的非 ASCII 字符 (»)
Python - Replace non-ascii character in string (»)
我需要将字符串中的字符“»”替换为空格,但仍然出现错误。这是我使用的代码:
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
# other code
soup = BeautifulSoup(data, 'lxml')
mystring = soup.find('a').text.replace(' »','')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in
position 13: ordinal not in range(128)
但是如果我用其他脚本测试它:
# -*- coding: utf-8 -*-
a = "hi »"
b = a.replace('»','')
有效。这是为什么?
为了使用str.replace()
方法替换字符串的内容;您需要先解码字符串,然后替换文本并将其编码回原始文本:
>>> a = "hi »"
>>> a.decode('utf-8').replace("»".decode('utf-8'), "").encode('utf-8')
'hi '
您也可以使用以下正则表达式从字符串中删除所有非 ASCII 字符:
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r'', 'hi »')
'hi '
@Moinuddin Quadri 的回答更适合您的用例,但一般来说,从给定字符串中删除非 ASCII 字符的简单方法是执行以下操作:
# the characters '¡' and '¢' are non-ASCII
string = "hello, my name is ¢arl... ¡Hola!"
all_ascii = ''.join(char for char in string if ord(char) < 128)
这导致:
>>> print(all_ascii)
"hello, my name is arl... Hola!"
您也可以这样做:
''.join(filter(lambda c: ord(c) < 128, string))
但这比 char for char ...
方法慢了大约 30%。
我需要将字符串中的字符“»”替换为空格,但仍然出现错误。这是我使用的代码:
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
# other code
soup = BeautifulSoup(data, 'lxml')
mystring = soup.find('a').text.replace(' »','')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 13: ordinal not in range(128)
但是如果我用其他脚本测试它:
# -*- coding: utf-8 -*-
a = "hi »"
b = a.replace('»','')
有效。这是为什么?
为了使用str.replace()
方法替换字符串的内容;您需要先解码字符串,然后替换文本并将其编码回原始文本:
>>> a = "hi »"
>>> a.decode('utf-8').replace("»".decode('utf-8'), "").encode('utf-8')
'hi '
您也可以使用以下正则表达式从字符串中删除所有非 ASCII 字符:
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r'', 'hi »')
'hi '
@Moinuddin Quadri 的回答更适合您的用例,但一般来说,从给定字符串中删除非 ASCII 字符的简单方法是执行以下操作:
# the characters '¡' and '¢' are non-ASCII
string = "hello, my name is ¢arl... ¡Hola!"
all_ascii = ''.join(char for char in string if ord(char) < 128)
这导致:
>>> print(all_ascii)
"hello, my name is arl... Hola!"
您也可以这样做:
''.join(filter(lambda c: ord(c) < 128, string))
但这比 char for char ...
方法慢了大约 30%。