簡體   English   中英

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'編解碼器無法對位置13中的字符u'\\ xbb'進行編碼:序數不在范圍內(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%。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM