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

2024-05-16 21:52:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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"}

我试过替换功能,但没用。在

^{pr2}$

Tags: orandthetokeyforwithare
3条回答

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

它试图将字符串编码为ASCII,第二个参数ignore告诉它忽略不能转换的字符(所有Unicode字符),而不是像通常没有第二个参数时那样引发异常,因此它返回的字符串只包含可以成功转换的字符,从而删除所有Unicode字符。在

用法示例:

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

更多信息:Python文档中的^{}Unicode。在

为了删除由unicode转义序列表示的字符,需要使用unicode字符串。在

例如

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

然而,正如人们在评论中提到的,删除版权符号可能是一个非常糟糕的主意,尽管这取决于您实际对字符串做了什么。在

d['key'].decode('unicode-escape').encode('ascii', 'ignore')

就是你要找的

^{pr2}$

相关问题 更多 >