AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Compare Strings with Python

PARTAGEZ

Comparing Python Strings is a common programming task that is used every day. This includes interpreting user input, verifying large data sets, and working with text-based protocols. Discover with us several solutions allowing you to compare Strings with Python, each time illustrated by examples.

Comparing Strings with Python: operators and functions

Python offers its users several operators for comparing Strings, as well as a range of predefined functions used to make comparing them easier and faster. Let’s first look at the operators, before reviewing the different comparison methods. Next will come two code examples, which we will use to illustrate how these operators and methods work.

Comparison operators

To compare Strings with Python, the simplest solution is to use Python operators. As in the case of integers or floats, comparison operators can be used to check similarities between Strings. In such a context, however, certain operators do not work as for these numbers; indeed, regarding Strings, it is possible to compare different properties. In the table below, you will find a quick presentation of the comparison operators and their respective operation.

Operator Meaning Example Return value
== Similar strings “Bonjour” == “bonjour” fake
!= Different thongs “Bonjour” != “bonjour” TRUE
< Lexicographic order (lower) “Australie” < “Zimbabwe” TRUE
> Lexicographic order (higher) “Australie” > “Zimbabwe” fake
<= Lexicographic order (lower or equal) “Danemark” <= “Amérique” fake
>= Lexicographical order (higher or equal) “Danemark” <= “Danemark” TRUE

Here, “lexicographic order” is a technical term synonymous with “alphabetical order” ; they therefore have the same meaning. Words with lower lexicographic order appear earlier in the alphabet than words with higher lexicographic order. For example, the lexicographic order of the String “abcd” is therefore lower than that of the String “xyz”.

Empty spaces within a String correspond to characters with a lower lexicographic order. By using the first characters of a String as a Python Substring, the lexicographic order of it will always be lower than that of the original String. For example, the lexicographic order of the String “Alex” is lower than that of the String “Alexander”.

Attention : the lexicographic order used with Python does not always correspond to the alphabetical order that you may be used to. Python notably considers that the expression “a < b” must return “true”, but that the expression “a < B” will return “false”. Indeed, in the ASCII and Unicode standards, uppercase letters are systematically encoded with lower values ​​than lowercase letters.

In addition to comparing Strings, text formatting is an important component for many programs. Check out our article on String Format methods in Python to learn more about the most important formatting methods and operators.

Comparison methods

Comparison operators aren’t the only ones that allow you to compare Strings; certain integrated methods are also provided for this purpose, for a comparison based on other criteria:

Method Description Example Return value
.startswith() Returns “true” if the first letters of a String match another String “Benjamin”.startswith(“Ben”) TRUE
.endswith() Returns “true” if the last letters of a String match another String “Benjamin”.endswith(“jasmin”) fake
.find() Returns the index of the first occurrence of a Substring; in case of non-occurrence of the Substring, “-1” is returned “Benjamin”.find(“jamin”) 4

Comparing Strings with Python: Code Examples

To illustrate how the operators and methods described above work, let us show you two examples. One is easy, but the other is a little more complex.

Check if a list is sorted alphabetically

In the example below, the program receives text input and uses it to create a list. Then, it uses comparison operators to verify that the list is sorted alphabetically.

liste_de_saisie = []
while(True):
    temp = input('Veuillez entrer un mot. Si vous ne souhaitez plus entrer de mots, veuillez entrer \'.\'')
    if temp == '.':
        break
    liste_de_saisie.append(temp)
print('Votre saisie : ', liste_de_saisie)

i = 0
alph = 1
while(i < len(liste_de_saisie) - 1):
    if(liste_de_saisie[i] > liste_de_saisie[i + 1]):
        print('Cette liste n'est pas triée par ordre alphabétique !')
        alph = 0
        break
    i = i + 1

if(alph == 1):
    print('Cette liste est triée par ordre alphabétique.')

Python

People database with search function

This example is more complex. The user is invited to enter the first and last names of the people concerned. They are added to a list then integrated into another, larger list. A nested list is then created; each sublist that composes it contains the first and last name of a person. Then the big list is sorted alphabetically, based on last names. The user can then re-enter text to search for people in the database. To do this, simply use the “.find()” comparison method.

personnes = []
while(True):
    temp = input('Veuillez saisir le nom de famille de la personne. Si vous ne souhaitez plus saisir de personnes, veuillez saisir \'.\'')
    if temp == '.':
        break
    personne = []
    personne.append(temp)
    temp = input('Veuillez saisir le prénom de la personne.')
    personne.append(temp)
    personnes.append(personne)
print('Votre saisie: ', personnes)


# Trier
personnes.sort()
print('Trié : ', personnes)


# Fonction de recherche
while(True):
    search = input('Veuillez saisir une chaîne pour effectuer une recherche dans la base de données. Si vous ne souhaitez plus rechercher de personnes, veuillez saisir \'.\'''.)
    if search == '.':
        break
    for i in personnes:
        if(i[0].find(search) != -1 or i[1].find(search) != -1):
            print('Match trouvé : ', i[0], ', ', i[1])

Python

Looking to get your web application online quickly and easily? Nothing could be easier: Deploy Now is the IONOS solution you need.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact