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个英文字母,而其他方法要处理所有字符(包括特殊符号等等),这样其他方法处理的字符数量比正则这种方法要多
相关推荐
abc123456sdggfd4 分钟前
bootstrap如何修改输入框获取焦点时的光晕
jvm·数据库·python
qq_330037999 分钟前
如何配置ASM元数据备份_md_backup与md_restore重建磁盘组结构
jvm·数据库·python
昭昭日月明14 分钟前
前端仔速通 Python
javascript·python
a95114164234 分钟前
SQL触发器实现自动生成流水号_配合序列对象实现递增逻辑
jvm·数据库·python
|_⊙38 分钟前
C++ 智能指针
开发语言·c++
哦哦~92138 分钟前
FDTD 与 Python 联合仿真的超表面智能设计技术与应用
python·fdtd·超表面
财经资讯数据_灵砚智能39 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年4月21日
人工智能·python·信息可视化·自然语言处理·ai编程
电子科技圈41 分钟前
IAR作为Qt Group独立BU携两项重磅汽车电子应用开发方案首秀北京车展
开发语言·人工智能·汽车·软件工程·软件构建·代码规范·设计规范
代码中介商42 分钟前
C语言指针深度解析:从数组指针到函数指针
c语言·开发语言
解救女汉子44 分钟前
mysql如何配置元数据锁超时_mysql lock_wait_timeout设置
jvm·数据库·python