I have a string that looks like so:
6Â 918Â 417Â 712
The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called s
, we get:
s.replace('Â ', '')
That should do the trick. But of course it complains that the non-ASCII character '\xc2'
in file blabla.py is not encoded.
I never quite could understand how to switch between different encodings.
Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
The code:
f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Â 918Â 417Â 712
s.replace('Â ','')
save_main_count(s)
It gets no further than s.replace
...
and make your
.py
file unicode.For what it was worth, my character set was
utf-8
and I had included the classic "# -*- coding: utf-8 -*-
" line.However, I discovered that I didn't have Universal Newlines when reading this data from a webpage.
My text had two words, separated by "
\r\n
". I was only splitting on the\n
and replacing the"\n"
.Once I looped through and saw the character set in question, I realized the mistake.
So, it could also be within the ASCII character set, but a character that you didn't expect.
Python 2 uses
ascii
as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 usesutf-8
as the default encoding for source files, so this is less of an issue.See: http://docs.python.org/tutorial/interpreter.html#source-code-encoding
To enable utf-8 source encoding, this would go in one of the top two lines:
The above is in the docs, but this also works:
Additional considerations:
The source file must be saved using the correct encoding in your text editor as well.
In Python 2, the unicode literal must have a
u
before it, as ins.replace(u"Â ", u"")
But in Python 3, just use quotes. In Python 2, you canfrom __future__ import unicode_literals
to obtain the Python 3 behavior, but be aware this affects the entire current module.s.replace(u"Â ", u"")
will also fail ifs
is not a unicode string.string.replace
returns a new string and does not edit in place, so make sure you're using the return value as wellI know it's an old thread, but I felt compelled to mention the translate method, which is always a good way to replace all character codes above 128 (or other if necessary).
Usage : str.translate(table[, deletechars])
Starting with Python 2.6, you can also set the table to None, and use deletechars to delete the characters you don't want as in the examples shown in the standard docs at http://docs.python.org/library/stdtypes.html.
With unicode strings, the translation table is not a 256-character string but a dict with the ord() of relevant characters as keys. But anyway getting a proper ascii string from a unicode string is simple enough, using the method mentioned by truppo above, namely : unicode_string.encode("ascii", "ignore")
As a summary, if for some reason you absolutely need to get an ascii string (for instance, when you raise a standard exception with
raise Exception, ascii_message
), you can use the following function:The good thing with translate is that you can actually convert accented characters to relevant non-accented ascii characters instead of simply deleting them or replacing them by '?'. This is often useful, for instance for indexing purposes.
Using Regex:
This will print out
6 918 417 712