Python except for UnicodeError?

In my code, I get this error all the time ...

UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 390: character maps to <undefined> 

I tried to throw an exception from UnicodeError and UnicodeEncodeError, but nothing works, the problem is that the users enter, so I can not control what they put, so I need all the coding errors to display the print, which says the error instead program crash ...

 try: argslistcheck = argslist[0] if argslistcheck[0:7] != "http://": argslist[0] = "http://" + argslist[0] with urllib.request.urlopen(argslist[0]) as url: source = url.read() source = str(source, "utf8") except urllib.error.URLError: print("Couln't connect") source = "" except UnicodeEncodeError: print("There was an error encrypting...") source = "" 

Traceback:

 Traceback (most recent call last): ..... things leading up to error File "C:\path", line 99, in grab print(source) File "C:\Python33\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 390: character maps to <undefined> 
+4
source share
3 answers

Try:

source = str(source, encoding='utf-8', errors = 'ignore')

or check out this post .

+4
source

Printing error. Your Windows console does not support UTF-8 printing, you need to change the code page:

 chcp 65001 

This is a windows command, not a python command. You may need to switch fonts; Lucida Sans Console is a Unicode font that can handle many more glyphs.

+4
source

try replacing str () with this: source = source.encode('UTF-8')

+3
source

All Articles