Skip to main content
 首页 » 编程设计

python之我想从给定字典(python)中的字符串中删除\u00a9 、\u201d 和类似的字符。

2025年05月04日19tuyile006

d = { 
    "key": "Impress the playing crowd with these classic " 
           "Playing Cards \u00a9 Personalized Coasters.These beautiful" 
           " coasters are made from glass, and measure approximately 4\u201d x 4\u201d (inches)" 
           ".Great to look at, and lovely to the touch.There are 4 coasters in a set.We have " 
           "created this exclusive design for all card lovers.Each coaster is a different suit, " 
           "with the underneath.Make your next Bridge, or Teen Patti session uber-personal!" 
           "Will look great on the bar, or any tabletop.Gift Designed for: Couples, Him, " 
           "HerOccasion:Diwali, Bridge, Anniversary, Birthday"} 

我已经尝试了它的替换功能,但没有用。

s = d[key].replace('\u00a9','') 

请您参考如下方法:

如果要从字符串中删除所有 Unicode 字符,可以使用 string.encode("ascii", "ignore")。

它尝试将字符串编码为 ASCII,第二个参数 ignore 告诉它忽略无法转换的字符(所有 Unicode 字符),而不是像通常那样抛出异常没有第二个参数,因此它返回一个仅包含可以成功转换的字符的字符串,从而删除所有 Unicode 字符。

示例用法:

unicodeString = "Héllò StàckOvèrflow" 
print(unicodeString.encode("ascii", "ignore")) # prints 'Hll StckOvrflow' 

更多信息:str.encode()和 Unicode在 Python 文档中。