10
votes

i have a string "Mikael Håfström" which contains some special characters how do i remove this using python?

3
Is your string a unicode string? Do you want to remove the characters or rather replace by "standard" characters? - Sven Marnach
Every character is special in its own way. - Ignacio Vazquez-Abrams

3 Answers

12
votes

You can use the unicodedata module to normalize unicode strings and encode them in their ASCII form like so:

>>> import unicodedata
>>> source = u'Mikael Håfström'
>>> unicodedata.normalize('NFKD', source).encode('ascii', 'ignore')
'Mikael Hafstrom'

One notable exception is that the letters 'đ' and 'Đ' are not recognized by Python and they do not get encoded to 'd', so they will simply be omitted from the result. That's a voiced alveolo-palatal affricate present in the latin alphabet of some SEE languages, so it may or may not immediately concern you based on your audience or whether or not your providing full support for the Latin-1 character set. I currently have Python 2.6.5 (Mar 19 2010) running locally and the issue is present, though I'm sure it may have been resolved with newer releases.

5
votes

For example using the encode method: u"Mikael Håfström".encode("ascii", "ignore")

1
votes

See this effbot article (includes code). It makes reasonable transliterations into ASCII characters where possible. It is possible to extend the built-in conversion table to handle many other characters (e.g. those used in Eastern European languages) that don't have a canonical decomposition.