Vérifier si une chaîne Python contient une autre chaîne

La manipulation de chaînes de caractères est une tâche courante dans n’importe quel langage de programmation. Python offre deux façons courantes de vérifier si une chaîne contient une autre chaîne.

Vérifier si une chaîne contient une autre chaîne en Python

Python prend en charge l’opérateur in. Nous pouvons donc l’utiliser pour vérifier si une chaîne fait partie d’une autre chaîne ou non. La syntaxe de l’opérateur in est la suivante :

sub in str

Il renvoie True si la sous-chaîne est partie de la chaîne principale, sinon il renvoie False. Regardons quelques exemples d’utilisation de l’opérateur in en Python.

str1 = 'I love Python Programming'

str2 = 'Python'

str3 = 'Java'

print(f'"{str1}" contains "{str2}" = {str2 in str1}')
print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() in str1}')
print(f'"{str1}" contains "{str3}" = {str3 in str1}')

if str2 in str1:
    print(f'"{str1}" contains "{str2}"')
else:
    print(f'"{str1}" does not contain "{str2}"')

Sortie :

"I love Python Programming" contains "Python" = True
"I love Python Programming" contains "python" = False
"I love Python Programming" contains "Java" = False
"I love Python Programming" contains "Python"

Si vous n’êtes pas familier avec les chaînes préfixées par ‘f’ en Python, c’est une nouvelle méthode pour le formatage des chaînes introduite dans Python 3.6. Vous pouvez en savoir plus à ce sujet sur les f-strings en Python.

Lorsque nous utilisons l’opérateur in, il appelle internement la fonction __contains__(). Nous pouvons également utiliser cette fonction directement, cependant il est recommandé d’utiliser l’opérateur in pour des raisons de lisibilité.

s = 'abc'

print('s contains a =', s.__contains__('a'))
print('s contains A =', s.__contains__('A'))
print('s contains X =', s.__contains__('X'))

Sortie :

s contains a = True
s contains A = False
s contains X = False

Utilisation de find() pour vérifier si une chaîne contient une autre sous-chaîne

Nous pouvons également utiliser la fonction find() de la chaîne pour vérifier si la chaîne contient une sous-chaîne ou non. Cette fonction renvoie la première position d’index où la sous-chaîne est trouvée, sinon elle renvoie -1.

str1 = 'I love Python Programming'

str2 = 'Python'

str3 = 'Java'

index = str1.find(str2)
if index != -1:
    print(f'"{str1}" contains "{str2}"')
else:
    print(f'"{str1}" does not contain "{str2}"')

index = str1.find(str3)
if index != -1:
    print(f'"{str1}" contains "{str3}"')
else:
    print(f'"{str1}" does not contain "{str3}"')

Sortie :

"I love Python Programming" contains "Python"
"I love Python Programming" does not contain "Java"

Vous pouvez consulter le script Python complet et d’autres exemples en Python depuis notre Dépôt GitHub.

Source:
https://www.digitalocean.com/community/tutorials/python-check-if-string-contains-another-string