简体   繁体   中英

Python: Replace non ascii characters in a list of strings

I understand there are many non ascii characters questions on stackoverflow but since I'm a total newb I've had no luck in successfully implementing them, plus I find the whole 'unicode' concept difficult to understand.

So I have a list -

mylist = ["apple", "samsung", "toshiba", "Don’t know", "Can’t recall"] 

I would like to access the single quote marks at index 3 and 4 and replace them with an apostrophe.

I tried this:

# -*- coding: utf-8 -*-
mylist = ["hello", "don't know", "Don’t know", "Can't recall"]
for word in mylist:
    word.replace(u"’", "'")
print mylist

I get the following error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 3: ordinal not in range(128)

Not sure if this is useful but I am using python version 2.x and I know that this problem may not occur if I was using version 3.

Thanks!

>>> mylist = ["apple", "samsung", "toshiba", "Don’t know", "Can’t recall"]
>>> [item.replace('\xe2\x80\x99',"'") for item in mylist]
['apple', 'samsung', 'toshiba', "Don't know", "Can't recall"]

If all the items are already unicode:

>>> mylist = [u"apple", u"samsung", u"toshiba", u"Don’t know", u"Can’t recall"]
>>> [item.replace(u'’',u"'") for item in mylist]
[u'apple', u'samsung', u'toshiba', u"Don't know", u"Can't recall"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM