23

My output looks like 'àéêöhello!'. I need change my output like this 'aeeohello', Just replacing the character à as a like this.

1

3 Answers 3

45

Please Use the below code:

import unicodedata

def strip_accents(text):
    try:
        text = unicode(text, 'utf-8')
    except NameError: # unicode is a default on python 3 
        pass

    text = unicodedata.normalize('NFD', text)\
           .encode('ascii', 'ignore')\
           .decode("utf-8")

    return str(text)

s = strip_accents('àéêöhello')

print s
5
  • 1
    Works perfectly. Thank you. Dec 26, 2017 at 20:48
  • 2
    Doesn't work for all the letters (Đ, ı, ł just to name some).
    – Fejs
    Oct 26, 2020 at 5:29
  • Why str(text)? normalize seems to return a string(Python 3.9). Dec 12, 2020 at 3:53
  • 6
    NameError: name 'unicode' is not defined python 3.8
    – TomSawyer
    Jan 19, 2021 at 9:44
  • Works without the block try (text = unicode(text, 'utf-8') gets an error. Thanks for the code.
    – erfelipe
    Jan 30, 2021 at 0:19
12
import unidecode

somestring = "àéêöhello"

#convert plain text to utf-8
u = unicode(somestring, "utf-8")
#convert utf-8 to normal text
print unidecode.unidecode(u)

Output:

aeeohello
6

Alpesh Valaki's answer is the "nicest", but I had to do some adjustments for it to work:

# I changed the import
from unidecode import unidecode

somestring = "àéêöhello"

#convert plain text to utf-8
# replaced unicode by unidecode
u = unidecode(somestring, "utf-8")

#convert utf-8 to normal text
print(unidecode(u))
1
  • This works for me trying to get stuff like: 'Đà Nẵng' into 'Da Nang' - thanks!
    – g0h
    Oct 15, 2022 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.