Python | Comprobar si una substring está presente en una string dada

En este artículo, cubriremos cómo verificar si una string de Python contiene otra string o una substring en Python. 

Dadas dos strings, compruebe si hay una substring en la string dada o no. 

Example 1: Input : Substring = "geeks" 
           String="geeks for geeks"
Output : yes
Example 2: Input : Substring = "geek"
           String="geeks for geeks"
Output : yes

¿Python tiene una string que contiene el método de substring?

Sí, verificar una substring es una de las tareas más utilizadas en python. Python usa muchos métodos para verificar una string que contiene una substring como, find(), index(), count(), etc. El método más eficiente y rápido es usar un operador » in » que se usa como operador de comparación. Aquí cubriremos diferentes enfoques como:

Método 1: Verifique la substring usando if… in.

Python3

# Take input from users
MyString1 = "A geek in need is a geek indeed"
 
if "need" in MyString1:
    print("Yes! it is present in the string")
else:
    print("No! it is not present")
Producción

Yes! it is present in the string

Método 2: Comprobación de la substring mediante el método split()

Comprobando si una substring está presente en la string dada o no sin usar ninguna función incorporada. Primero divida la string dada en palabras y guárdelas en una variable s y luego use la condición if para verificar si una substring está presente en la string dada o no.

Python3

# Python code
# To check if a substring is present in a given string or not
 
# input strings str1 and substr
string = "geeks for geeks"  # or string=input() -> taking input from the user
substring = "geeks"  # or substring=input()
 
# splitting words in a given string
s = string.split()
 
# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
    print("yes")
else:
    print("no")
Producción

yes

Método 3: Verifique la substring usando el método find()

Podemos verificar iterativamente cada palabra, pero Python nos proporciona una función incorporada find() que verifica si una substring está presente en la string, lo que se hace en una línea. La función find() devuelve -1 si no se encuentra, de lo contrario, devuelve la primera aparición, por lo que el uso de esta función puede resolver este problema. 

Python3

# function to check if small string is
# there in big string
 
 
def check(string, sub_str):
    if (string.find(sub_str) == -1):
        print("NO")
    else:
        print("YES")
 
 
# driver code
string = "geeks for geeks"
sub_str = "geek"
check(string, sub_str)
Producción

YES

Método 4: verificar la substring usando el método «contar()»

También puede contar el número de ocurrencias de una substring específica en una string, luego puede usar el método Python count(). Si no se encuentra la substring, se imprimirá «sí», de lo contrario, se imprimirá «no».

Python3

def check(s2, s1):
    if (s2.count(s1) > 0):
        print("YES")
    else:
        print("NO")
 
 
s2 = "A geek in need is a geek indeed"
s1 = "geeks"
check(s2, s1)
Producción

NO

Método 5: Verifique la substring usando el método index()

El método .index() devuelve el índice inicial de la substring pasada como parámetro. Aquí » substring » está presente en el índice 16.

Python3

any_string = "Geeks for Geeks substring "
start = 0
end = 1000
print(any_string.index('substring', start, end))

Producción:

16

Método 6: verifique la substring usando la clase mágica «__contains__».

Python String __contiene__(). Este método se utiliza para verificar si la string está presente en la otra string o no. 

Python3

a = ['Geeks-13', 'for-56', 'Geeks-78', 'xyz-46']
for i in a:
    if i.__contains__("Geeks"):
        print(f"Yes! {i} is containing.")
Producción

Yes! Geeks-13 is containing.
Yes! Geeks-78 is containing.

Método 7: Verifique la substring usando expresiones regulares 

RegEx se puede usar para verificar si una string contiene el patrón de búsqueda especificado. Python tiene un paquete integrado llamado re , que se puede usar para trabajar con expresiones regulares. 

Python3

# When you have imported the re module,
# you can start using regular expressions.
import re
 
# Take input from users
MyString1 = "A geek in need is a geek indeed"
MyString2 = "geeks"
 
# re.search() returns a Match object
# if there is a match anywhere in the string
if re.search(MyString2, MyString1):
    print("YES,string '{0}' is present in string '{1}'" .format(
        MyString2, MyString1))
else:
    print("NO,string '{0}' is not present in string '{1}' " .format(
        MyString2, MyString1))
Producción

NO,string 'geeks' is not present in string 'A geek in need is a geek indeed' 

Publicación traducida automáticamente

Artículo escrito por Striver y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *