如何在不使用任何方法或函数的情况下实现.split的字符串版本?

2024-04-19 14:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我被要求的

写一个名为str的文件_红色.py它实现了字符串方法find和split的版本,而不使用任何字符串方法或函数。在

特别是,定义一个函数myfind,使myfind(s,t)执行与s.find(t)相同的操作;定义一个函数mysplit,使mysplit(s,t)执行与s.split(t)相同的操作。在

您不能在解决方案中使用任何字符串方法。所有运营商(包括in、[index]、[i1:i2]等)都是公平博弈。任何函数(或文件本身)都不应打印任何内容或请求任何输入。在

除了功能正确性之外,还将保留一些要点

有好的变量名 为您编写的所有函数提供有意义的docstring

def myfind(whole,part):
"""Docstring: searches for a string (whole) for a segment which is (part) and returns the index"""

    if part in whole:
        for n in range(len(whole)):
            sub = whole[n:n+len(part)]

            if part in sub: #Use of if-in function to find out if our segment is in our word
                return n
                break
    else:
        return -1 # Doesn't exist within the string


def mysplit(whole, part):
    """Docstring: when given a word, will seperate the word into predetermined chunks"""

    split_word = []
    position_start = 0
    while part in whole [position_start::]:
        new_position = myfind(whole,part)
        split_segment = whole[position_start: new_position+position_start]
        split_word.append(split_segment)
        if new_position == -1:
            break
        position_start = new_position+len(part)+position_start
    split_word.append(whole[position_start:])
    return split_word

测试时:

^{pr2}$

我得到:

0
3
-1

['', '', '', '', '', '', '', '']
['div', 'ed']
['divided']

应该的时间:

0
3
-1

['', 'ivi', 'e', '']
['div', 'ed']
['divided']

有人知道我做错了什么吗?我知道我的错误在代码的第二部分,但我不确定在哪里。


Tags: 方法函数字符串innewifsegmentposition
2条回答

这是你问题的另一种解决办法。在

def splitter(mystr, char=','):
    var = ''
    n = len(mystr)
    for idx, i in enumerate(mystr, 1):
        if i != char:
            var += i
        if (i == char) or (idx == n):
            yield var
            var = ''

res = list(splitter('Hello, this is a test, see if it works!'))

# ['Hello', ' this is a test', ' see if it works!']

此行new_position = myfind(whole,part)将始终返回0,因为您每次都在测试相同的内容。在

new_position = myfind(whole[position_start:], part)我相信这就是你的想法。在

相关问题 更多 >