python - Python 中的连续子字符串

标签 python string substring

我需要在像ACACA这样的字符串中找到像'ACA'这样的子字符串的数量。我试过count(str)方法,但它只给了我 1 而不是 2。我怎样才能找到这些字符串在 python 中的实际出现次数?

最佳答案

count 的文档 method of strings说:

Return the number of non-overlapping occurrences of substring sub in the range [start, end].

您的子字符串重叠,这就是为什么 count 方法没有执行您想要的操作。您可以使用 find 方法的可选参数从字符串开头以外的位置开始查找计数:

string = 'ACACA'
substr = 'ACA'

substr_count = 0
start = 0
while True:
    loc = string.find(substr, start)
    if loc == -1:
        break
    substr_count += 1
    start = loc + 1

该例程的循环计数与字符串中子字符串的出现次数相同。您可以使用一个更简单的例程来检查字符串的每个位置,以查看子字符串是否位于该位置,但这需要更多循环并且速度会更慢。

关于python - Python 中的连续子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690245/

相关文章:

python - 为什么 3<<1 == 6 在 python 中?

java - 复选框标签到字符串

XSLT - 检查子字符串

java - 从索引中获取仅包含可用字符的子字符串

python - C 和 Python 哪个更好?

python - 将 sys.stdout 重定向到 python 日志记录

python - 使用 Django 和单一网页模板在数据库中存储网页内容的最佳方法

javascript - 将\n 替换为 <br> 并将\r\n 替换为 javascript 中的 <p>

c - 在 C 中有 char 指针时的 strcpy

java - 创建我自己的 String 类/子字符串方法