Removing non-breaking spaces from strings using Python

You don’t have a unicode string, but a UTF-8 list of bytes (which are what strings are in Python 2.x).

Try

myString = myString.replace("\xc2\xa0", " ")

Better would be to switch to unicode — see this article for ideas. Thus you could say

uniString = unicode(myString, "UTF-8")
uniString = uniString.replace(u"\u00A0", " ")

and it should also work (caveat: I don’t have Python 2.x available right now), although you will need to translate it back to bytes (binary) when sending it to a file or printing it to a screen.

Leave a Comment