python统计字符串中大小写字符个数的性能实测与分析

给定一个字符串,统计字符串中大写字符个数,有如下三种方法:

python 复制代码
# method1
s1 = len(re.findall(r'[A-Z]',content))
# method2
s2 = sum(1 for c in content if c.isupper())
# method3
s3 = 0
for c in content:
    if c.isupper()==True:
        s3+=1

经过多次实测后,方法1是最快的,方法3是最慢的。下面是其中某一次的实际时间消耗:

复制代码
(method1) upper char count by re:0.11256217956542969s
(method2) upper char count by for-sum:0.36724019050598145s
(method3) upper char count by for-loop:0.5580060482025146s

改为统计字符串中大写字符个数和小写字符个数后:

python 复制代码
s11 = len(re.findall(r'[A-Z]',content))
s12 = len(re.findall(r'[a-z]',content))


s21 = sum(1 for c in content if c.isupper())
s22 = sum(1 for c in content if c.isupper())


s3 = 0
s4 = 0
for c in content:
    if c.isupper()==True:
        s3+=1
    else:
        s4+=1

性能也满足上面的规律:

复制代码
upper char count by re:0.40007758140563965s
upper char count by for-sum:0.6471347808837891s
upper char count by for-loop:0.918128252029419s

原因分析:

  • 正则表达式在匹配上是有算法优化过的
  • 正则只处理26个英文字母,而其他方法要处理所有字符(包括特殊符号等等),这样其他方法处理的字符数量比正则这种方法要多
相关推荐
reasonsummer8 小时前
【办公类-115-01】20260906育儿知识(家园小报)批量制作(2026年9月-2027年6月)
开发语言·数据库·c#
君顾18 小时前
智慧场馆解决方案小程序系统实战:从架构设计到上线指南
java·开发语言·智慧场馆
zhougl9968 小时前
Dockerfile实战教程
java·开发语言·spring boot
FfHUCisI8 小时前
Golang 网络轮询器 netpoll:把阻塞 IO 变成事件通知
开发语言·网络·golang
XiaoQiao6669998 小时前
C 语言常用头文件及里面核心函数
c语言·开发语言
AC赳赳老秦8 小时前
环保监测公开数据应用:OpenClaw 抓取空气与水质公开监测数据,开展区域环境质量趋势分析
大数据·数据库·人工智能·python·php·deepseek·openclaw
statistican_ABin8 小时前
中国宠物经济发展分析报告——基于R语言的2018-2024年宠物市场多维度分析
开发语言·r语言·宠物
RSABLOCKCHAIN8 小时前
打造工业级多智能体量化交易闭环:基于 Alpaca、LangGraph 与双轨执行的智能投资与持仓治理系统
人工智能·python·ai·aigc
用户019027581618 小时前
如何用 Python 做多因子打分选股?
python
烂蜻蜓8 小时前
Flask入门教程(三十一):实用函数与类API——全局工具函数速查
后端·python·flask