You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何按交替规则提取字符串中的大小写字母?

Python交替提取大小写字母解法整理

首先你原有代码存在边界值遗漏问题:用"A" < i < "Z"判断会漏掉A、Z两个大写字母,小写判断同理,推荐优先用字符串自带的isupper()/islower()方法,准确性和可读性都更高。

方案1:简化迭代写法(最易理解)

str_a = "ifeFemFEkej83FkW"
res, need_upper = "", True
for c in str_a:
    if need_upper and c.isupper():
        res += c
        need_upper = False
    elif not need_upper and c.islower():
        res += c
        need_upper = True
print(res)

方案2:正则表达式解法

直接用正则匹配「大写+后续首个小写」的组合,拼接后直接得到结果:

import re
str_a = "ifeFemFEkej83FkW"
res = ''.join(re.findall(r'[A-Z](?:[^a-z]*([a-z]))?', str_a))
print(res)

方案3:一行式实现(Python3.8+支持海象运算符)

str_a = "ifeFemFEkej83FkW"
res = ''.join([c for c in str_a if (need_upper:=getattr(locals(), 'need_upper', True)) and c.isupper() and not (need_upper:=False) or not need_upper and c.islower() and (need_upper:=True)])
print(res)

内容的提问来源于stack exchange,提问作者dean89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:15:05