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

EPAM Python入门课程:实现str.split替代函数遇问题求助

问题分析与解决方法

问题原因

你实现的自定义split函数,在处理maxsplit=1的场景时,找到第一组连续空格的结束位置后,直接将该位置之后的全部内容作为第二个元素返回,没有跳过后续连续的分隔符(空格),导致结果中保留了前置空格。

解决思路

当触发maxsplit限制时,找到第一个分割的结束位置后,需要继续向后遍历字符串,跳过所有连续的分隔符,直到遇到非分隔符字符,再从该位置开始截取剩余内容。

修正后的示例代码

以默认分隔符(任意连续空白字符)为例,修正后的函数实现如下:

def my_split(s, sep=None, maxsplit=-1):
    # 处理默认分隔符为任意空白字符的情况
    if sep is None:
        result = []
        current_word = []
        split_count = 0
        # 遍历字符串,逐个处理字符
        for idx, char in enumerate(s):
            if char.isspace():
                # 如果当前有正在构建的单词,且未达到maxsplit限制
                if current_word and (maxsplit == -1 or split_count < maxsplit):
                    result.append(''.join(current_word))
                    current_word = []
                    split_count += 1
                    # 跳过后续连续的空格,直到找到非空格字符
                    while idx + 1 < len(s) and s[idx+1].isspace():
                        idx += 1
            else:
                # 若已达到maxsplit限制,直接截取剩余所有内容并结束
                if split_count == maxsplit:
                    result.append(''.join(current_word) + s[idx:])
                    current_word = []
                    break
                current_word.append(char)
        # 处理最后一段未加入结果的内容
        if current_word:
            result.append(''.join(current_word))
        return result
    # 指定分隔符的逻辑可后续扩展
    else:
        pass

测试你的用例:

print(my_split('Python    2     3', maxsplit=1))
# 输出: ['Python', '2     3']

关键细节说明

  • 默认分隔符场景下,连续空白会被视为单个分隔符,分割后不会保留任何空白字符。
  • 触发maxsplit限制时,必须跳过第一个分割点后的所有连续分隔符,再截取剩余内容,才能确保结果符合原生split的行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:15:59