views:

270

answers:

3

I'm using the following regex basically to search for and delete these characters.

invalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)')

My source code in ascii encoded, and whenever I try to run the script it spits out:

SyntaxError: Non-ASCII character '\xdb' in file ./release.py on line 273, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

If i follow the instructions at the given website, and place on the second line encoding: utf-8, my script doesn't run. Instead it gives me this error.

SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xdb in position 0: unexpected end of data

I'm clearly lost if anyone could help me get that one regex running in an ascii written script that'd be great.

A: 

After telling Python that your source file uses UTF-8 encoding, did you actually make sure that your editor is saving the file using UTF-8 encoding? The error you get indicates that your editor is probably not using UTF-8.

What text editor are you using?

Greg Hewgill
I'm using notepad++
Incognito
Here's how to configure UTF-8 in Notepad++: http://superuser.com/questions/21135/how-can-i-edit-unicode-text-in-notepad
Greg Hewgill
A: 
\x{c0de}

In a regex will match the Unicode character at code point c0de.

Python uses PCRE, right? (If it doesn't, it's probably \uC0DE instead...)

Anon.
+3  A: 

You need to find out what encoding your editor is using, and set that per PEP263; or, make things more stable and portable (though alas perhaps a bit less readable) and use escape sequences in your string literal, i.e., use u'(\xdb|\xb2|\xb0|\xb1|\xc9|\xb9|\xcd)' as the parameter to the re.compile call.

Alex Martelli
I wouldn't use the byte representation of an Unicode char as it's really locale dependent. I'd escape as Unicode, and thus avoiding any complication.
Paulo Santos
@Paulo, Unicode encodings are **not** necessarily locale-dependent -- you can use `'utf-8'` or other locale-independent encodings. But in any case, the form I give above is what a `print repr(thestring)` emits, does **not** rely on any encoding, and cannot possibly cause any complications (it's just the same as using `\u00db` and so on, guaranteed to produce absolutely identical Unicode objects, just more concise as it saves you typing the unchanging `00` parts!-).
Alex Martelli