python – How do I validate if one string is inside another?

Question:

It often happens to me that I want to see if one string is inside another.

For example, I would like to know if the text "hello" is within the string "you are greeted, pepito, hello" or in "hello don pepito".

Is there a function like cadena.contains("bla") to say something like "se te saluda, pepito, hola".contains("hola") ?

Answer:

The idiomatic way to do this is to use the in operator:

if 'subcadena' in cadena:
    #          ^^
    # ...

If you happen to want to know where the substring occurs within the string, then you can use cadena.find(subcadena)

>>> 'hola'.find('X')
-1                    # no se encuentra
>>> 'hola'.find('l')
2                     # está en la posición 2 (empezando por 0)

You can also use the start and end parameters to indicate from where (and how far) you want to find the string:

>>> 'holala'.find('a')
3
>>> 'holala'.find('a', 4)
5
Scroll to Top