Dada una string y una substring, escriba un programa de Python para encontrar cuántos números de substrings hay en la string (incluidos los casos superpuestos). Analicemos algunos métodos a continuación.
Método #1: Usar el método re.findall()
Python3
# Python code to demonstrate # to count total number # of substring in string import re # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using re.findall res = len(re.findall('(?= aba)', ini_str)) # Printing result print("Number of substrings", res)
Método #2: Usar el método re.finditer()
Python3
# Python code to demonstrate # to count total number # of substring in string import re # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using re.finditer res = sum(1 for _ in re.finditer('(?= aba)', ini_str)) # Printing result print("Number of substrings", res)
Método #3: Usar empieza con()
Python3
# Python code to demonstrate # to count total number # of substring in string # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using startswith res = sum(1 for i in range(len(ini_str)) if ini_str.startswith("aba", i)) # Printing result print("Number of substrings", res)
Producción:
Number of substrings 4
Método #4: Usar el método count()
Python3
# Python code to demonstrate # to count total number # of substring in string # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using count def Countofoccurrences(ini_str,sub_str): # Initialize count and start to 0 count = 0 start = 0 # Search through the string till # we reach the end of it while start < len(ini_str): # Check if a substring is present from # 'start' position till the end pos = ini_str.find(sub_str, start) if pos != -1: # If a substring is present, move 'start' to # the next position from start of the substring start = pos + 1 # Increment the count count += 1 else: # If no further substring is present break # return the value of count return count # Printing result print("Number of substrings", Countofoccurrences(ini_str,sub_str))
Producción
Number of substrings 4
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA