Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 strings without considering accents in Python [duplicate]

Tags:

python

string

I would like to compare 2 strings and have True if the strings are identical, without considering the accents.

Example : I would like the following code to print 'Bonjour'

if 'séquoia' in 'Mon sequoia est vert':
    print 'Bonjour'
like image 264
Basj Avatar asked Dec 22 '13 13:12

Basj


People also ask

How do you compare two strings with case sensitive in Python?

String Equals Check in Python Example: s1 = 'String' s2 = 'String' s3 = 'string' # case sensitive equals check if s1 == s2: print('s1 and s2 are equal. ') if s1. __eq__(s2): print('s1 and s2 are equal.

How do you remove accent marks in Python?

We can remove accents from the string by using a Python module called Unidecode. This module consists of a method that takes a Unicode object or string and returns a string without ascents.

How do you check if two strings are exactly the same Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

Can we compare two strings using == in Python?

String Comparison using == in PythonThe == function compares the values of two strings and returns if they are equal or not. If the strings are equal, it returns True, otherwise it returns False.


2 Answers

You should use unidecode function from Unidecode package:

from unidecode import unidecode

if unidecode(u'séquoia') in 'Mon sequoia est vert':
    print 'Bonjour'
like image 65
Suor Avatar answered Oct 25 '22 05:10

Suor


You should take a look at Unidecode. With the module and this method, you can get a string without accent and then make your comparaison:

def remove_accents(data):
    return ''.join(x for x in unicodedata.normalize('NFKD', data) if x in string.ascii_letters).lower()


if remove_accents('séquoia') in 'Mon sequoia est vert':
    # Do something
    pass

Reference from stackoverflow

like image 39
Maxime Lorant Avatar answered Oct 25 '22 05:10

Maxime Lorant