2016-11-29 80 views
6

我需要用空格替換字符串「»」,但仍然出現錯誤。這是我使用的代碼:Python - 替換字符串中的非ASCII字符(»)

# -*- 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('»','') 

它的工作原理。爲什麼這個?

+1

谷歌搜索錯誤,你會得到它,我得到這個回來:http://stackoverflow.com/questions/5141559/unicodeencodeerror-ascii-codec-cant-encode-character-u-xef-in-position-0應該有些東西可以使用 –

回答

8

爲了用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 ' 
2

@Moinuddin誇德里的回答適合您的使用情況較好,但在一般情況下,一個簡單的方法來從給定的字符串中刪除非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%。