Python: controlla se la stringa contiene una sottostringa

Checking whether a string contains a substring aids to generalize conditionals and create more flexible code. Additionally, depending on your domain model – checking if a string contains a substring may also allow you to infer fields of an object, if a string encodes a field in itself.

In this guide, we’ll take a look at how to check if a string contains a substring in Pitone.

Il in Operatore

The easiest way to check if a Python string contains a substring is to use the in operatore.

Il in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring:

fullstring = "StackAbuse"
substring = "tack"

if substring in fullstring:
    print("Found!")
else:
    print("Not found!")

This operator is shorthand for calling an object’s __contains__ method, and also works well for checking if an item exists in a list. It’s worth noting that it’s not null-safe, so if our fullstring was pointing to None, an exception would be thrown:

TypeError: argument of type 'NoneType' is not iterable

To avoid this, you’ll first want to check whether it points to None o no:

fullstring = None
substring = "tack"

if fullstring != None and substring in fullstring:
    print("Found!")
else:
    print("Not found!")

Il String.index() metodo

The String type in Python has a method called index() that can be used to find the starting index of the first occurrence of a substring in a string.

If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except-else block:

fullstring = "StackAbuse"
substring = "tack"

try:
    fullstring.index(substring)
except ValueError:
    print("Not found!")
else:
    print("Found!")

This method is useful if you also need to know the position of the substring, as opposed to just its existence within the full string. The method itself returns the index:

print(fullstring.index(substring))

Though – for the sake of checking whether a string contains a substring, this is a verbose approach.

The String.find() Method

The String class has another method called find() which is more convenient to use than index(), mainly because we don’t need to worry about handling any exceptions.

If find() doesn’t find a match, it returns -1, otherwise it returns the left-most index of the substring in the larger string:

Dai un'occhiata alla nostra guida pratica e pratica per l'apprendimento di Git, con le migliori pratiche, gli standard accettati dal settore e il cheat sheet incluso. Smetti di cercare su Google i comandi Git e in realtà imparare esso!

fullstring = "StackAbuse"
substring = "tack"

if fullstring.find(substring) != -1:
    print("Found!")
else:
    print("Not found!")

Naturally, it performs the same search as index() and returns the index of the start of the substring within the parent string:

print(fullstring.find(substring))

Espressioni regolari (RegEx)

Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. With Regular Expressions, you can perform flexible and powerful searches through much larger search spaces, rather than simple checks, like previous ones.

Python is shipped with a built-in module for regular expressions, called re. re module contains a function called search(), which we can use to match a substring pattern:

from re import search

fullstring = "StackAbuse"
substring = "tack"

if search(substring, fullstring):
    print "Found!"
else:
    print "Not found!"

This method is best if you are needing a more complex matching function, like case insensitive matching, or if you’re dealing with large search spaces. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases.

L'autore

Questo articolo è stato scritto da Jacob Stopak, consulente software e sviluppatore con la passione di aiutare gli altri a migliorare la propria vita attraverso il codice. Jacob è il creatore di Impegno iniziale – un sito dedicato ad aiutare gli sviluppatori curiosi a scoprire come sono codificati i loro programmi preferiti. Il suo progetto in primo piano aiuta le persone impara Git a livello di codice.

Timestamp:

Di più da Impilamento