Python|计算字符串中子字符串数量的方法
给定一个字符串和一个子字符串,编写一个Python程序来找出字符串中有多少个子字符串(包括重叠的情况)。下面我们来讨论几种方法。
方法 #1:使用re.findall()
# 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)
输出:
Number of substrings 0
方法 #2:使用re.finditer()
# 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)
输出:
Number of substrings 0
方法#3:使用startswith()
# 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)
输出:
Number of substrings 4