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

如何将字符串分割为连续相同字符组成的子串?

如何将字符串分割为连续相同字符组成的子串?

这是个很实用的字符串处理场景,我来分享两种靠谱的实现思路,以Python为例:

方法一:手动遍历(直观易懂)

这种方法适合新手理解核心逻辑,一步步遍历字符串,把连续相同的字符攒成子串:

def split_consecutive_chars(s):
    if not s:
        return []
    result = []
    current_char = s[0]
    current_sub = current_char
    for char in s[1:]:
        if char == current_char:
            current_sub += char
        else:
            result.append(current_sub)
            current_char = char
            current_sub = char
    # 别忘了把最后一组加进去
    result.append(current_sub)
    return result

# 测试示例
print(split_consecutive_chars("hello"))  # 输出: ['h', 'e', 'll', 'o']
print(split_consecutive_chars("helel"))  # 输出: ['h', 'e', 'l', 'e', 'l']

方法二:用itertools.groupby(简洁高效)

Python标准库的itertools.groupby天生就是用来处理连续相同元素分组的,一行核心代码就能搞定:

from itertools import groupby

def split_consecutive_chars(s):
    return [''.join(group) for char, group in groupby(s)]

# 测试示例
print(split_consecutive_chars("hello"))  # 输出: ['h', 'e', 'll', 'o']
print(split_consecutive_chars("helel"))  # 输出: ['h', 'e', 'l', 'e', 'l']

小提醒

groupby是按连续相同的字符分组的,正好完美匹配你的需求。如果字符串里有非连续的相同字符(比如"hheelloo"),它也只会把连续的部分分到一组,完全符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:43:04