Python .replace() function wont work with accented characters

Viewed 27

Im using python's .replace() function to find and replace to words "à Lyon"but it doesnt seem to work with accented characters. I don want to replace "a Lyon" (wothout accent) only the occurences that have the "à" accented.

ex.

old_str = "nous allons à Lyon et malheureusement il a Lyon"
new_str = old_str.replace("à Lyon", "found it")

This should return: "nous allons found it et malheureusement il a Lyon"

Any sugestions would be very much appreciated thanks.

1 Answers

Try making the string you want to replace a unicode string by adding a u in front of the quotes.

it works for me either way, I am on python 3.10.6

old_str = "nous allons à Lyon et malheureusement il a Lyon"
new_str = old_str.replace(u"à Lyon", "found it") #now a unicode string
print(new_str)
Related