Skip to main content
 首页 » 编程设计

python之如何在不使用 .split 和 .strip 函数的情况下编写我自己的拆分函数

2025年05月04日9xiaohuochai

如何编写自己的拆分函数?我只是认为我应该删除空格、'\t' 和 '\n'。但是由于知识匮乏,我没有做这道题的想法

这是原始问题:

Write a function split(string) that returns a list of words in the given string. Words may be separated by one or more spaces ' ' , tabs '\t' or newline characters '\n' .

And there are examples:

words = split('duff_beer 4.00') # ['duff_beer', '4.00'] 
words = split('a b c\n') # ['a', 'b', 'c'] 
words = split('\tx y \n z ') # ['x', 'y', 'z'] 

Restrictions: Don't use the str.split method! Don't use the str.strip method

请您参考如下方法:

关于您问题的一些评论提供了非常有趣的想法来解决具有给定限制的问题。

但是假设你不应该使用任何 python 内置的 split 函数,这是另一个解决方案:

def split(string, delimiters=' \t\n'): 
    result = [] 
    word = '' 
    for c in string: 
        if c not in delimiters: 
            word += c 
        elif word: 
            result.append(word) 
            word = '' 
 
    if word: 
        result.append(word) 
 
    return result 

示例输出:

>>> split('duff_beer 4.00') 
['duff_beer', '4.00'] 
>>> split('a b c\n') 
['a', 'b', 'c'] 
>>> split('\tx y \n z ') 
['x', 'y', 'z']