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

标签 python python-3.x

如何编写自己的拆分函数?我只是认为我应该删除空格、'\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']

关于python - 如何在不使用 .split 和 .strip 函数的情况下编写我自己的拆分函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52495936/

相关文章:

python - 无法从 App Engine 中的 FTP 服务器下载 csv 文件

Python:根据位置获取行索引

python - Pandas - 与缺失值合并

python - 在 Pyglet 中使用 numpy 数组和 ctypes 进行 OpenGL 调用

python-3.x - Google Storage python api 并行下载

python - 提取数字和单词之间的文本

python - 获取字符串转换的枚举值

python - 在 pandas 中绘制部分堆积条形图

python - Python 中随机的字典数据类型

python - 如何将一组文档收集到 pandas 数据框中?