社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中找到字符串中的子字符串数

ptalebic • 6 年前 • 2007 次点击  

我有一个子串 'G^ATTC' 我想找出它在一个字符串中出现的时间 'ATCGCGATTC' 但我不能因为 '^' .

我用过 re.findall ,但结果总是 0 .

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51961
文章 [ 2 ]  |  最新文章 6 年前
ncica
Reply   •   1 楼
ncica    7 年前

可能是这样的:

import re

txt = "ATCGCG1ATTCAAAAAAAAAAAAAG4ATTC"
substring =  'G^ATTC'
x = re.findall(substring.replace('^','.'), txt) # ['G1ATTC', 'G4ATTC']
print ("pattern {} occurs {} times".format(substring,len(x)))

输出:

pattern G^ATTC occurs 2 times
AmphotericLewisAcid
Reply   •   2 楼
AmphotericLewisAcid    7 年前

这是因为在Regex中,“^”字符表示“行的开始”。与此相关,“$”表示“行的结束”

所以,当它搜索“G^ATTC”时,它永远不会匹配任何东西,因为你说的“G”在行首之前(这甚至没有意义)。

修复regex的方法是包含一个“\”来转义“^”。这告诉regex将“^”作为字符而不是行首。

所以,把它改成“G^ATTC”