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

2024-09-24 10:27:12 发布

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

如何编写自己的分割函数?我想我应该删除空格,'\t'和{}。但是由于知识的缺乏,我不想做这个问题

原来的问题是:

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


Tags: orthe函数stringusefunctionmethodwrite
3条回答

这就是你可以通过分配一个列表来完成的,这是在python3.6上测试的

下面只是一个例子。。在

values = 'This is a sentence'
split_values = []
tmp  = ''
for words in values:
    if words == ' ':
        split_values.append(tmp)
        tmp = ''
    else:
        tmp += words
if tmp:
    split_values.append(tmp)
print(split_values)

期望输出:

^{pr2}$

对你的问题的一些评论提供了非常有趣的想法来解决给定限制条件下的问题。在

但是假设您不应该使用任何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

输出示例:

^{pr2}$

我认为使用正则表达式也是最好的选择。在

我会试试这样的方法:

import re
def split(string):
    return re.findall('\S+',string)

这将返回字符串中所有非空白字符的列表。在

输出示例:

^{pr2}$

相关问题 更多 >