zhangjinzhou
zhangjinzhou

Reputation: 2701

How to catch a non-ASCII character error?

I am trying to catch this error SyntaxError: Non-ASCII character '\xc3' using this code:

try:
    address = 'ÁR11E'
except:
    print 'hello'

I can never get "hello" printed. The error is treated as unhandled and stops the process. How can I catch and handle this type of error?

I only have to catch the error without solving it for now.

Upvotes: 0

Views: 833

Answers (3)

zvone
zvone

Reputation: 19332

By default, Python 2 source code should contain only ASCII characters, therefore this is syntax error. You cannot catch it, because it makes the whole file invalid.

There are two things you can do:

# coding: utf-8

  • or encode the non-ascii character

address = '\xC3\x81R11E' # this would be utf-8

address = '\xC3\x81R11E'.decode('utf-8') # this would be unicode

or

address = u'\N{LATIN CAPITAL LETTER A WITH ACUTE}R11E'

or

address = u'\u0381R11E'

Upvotes: 4

Eldany03
Eldany03

Reputation: 11

1st line (linux)

!usr/bin/env python

2nd line (linux)

coding: utf-8

Upvotes: 1

Gelineau
Gelineau

Reputation: 2090

You cannot catch a syntax error in Python (except if it is raised from an eval, which is not your case)

Upvotes: 1

Related Questions