【问题标题】:Using split function without split() string method. Almost使用没有 split() 字符串方法的 split 函数。几乎
【发布时间】:2017-06-10 05:44:40
【问题描述】:

我正在尝试复制 .split() 字符串方法。它运作良好,但不包括最后一个字。

def stringSplitter(string):
    words = []
    current_word = ""
    for x in range(len(string)): #problem is here
        if string[x] == " ":
            words.append(current_word)
            current_word = ""
        else:
            current_word += string[x]
    return words

测试一:当句子=我喜欢骑自行车时,我的代码输出错误:

['I', 'like', 'to', 'ride', 'my']

我想要的结果是:

['I', 'like', 'to', 'ride', 'my', 'bicycle']

【问题讨论】:

  • 如果你在你的 python for 循环中使用索引,你通常做错了。

标签: python for-loop split


【解决方案1】:

在从函数返回之前添加words.append(current_word)。那是你的“丢失”词。此外,无需使用range 或任何索引。 for x in string: 直接遍历字符。

【讨论】:

  • 谢谢!最后,这就是我所缺少的。
【解决方案2】:

请注意,这可以使用生成器函数更简洁地实现 - 如果您不介意稍微偏离“真实的”str.split() 函数实现:

>>> def split(string, delimiter=' '):
    current_word = ''
    for char in string:
        if char == delimiter:
            yield current_word
            current_word = ''
        else:
            current_word += char
    yield current_word


>>> list(split('I like to ride my bicycle'))
['I', 'like', 'to', 'ride', 'my', 'bicycle']
>>> 

您甚至可以修改它以允许返回分隔符:

>>> def split(string, delimiter=' ', save_delimiter=False):
    current_word = ''
    for char in string:
        if char == delimiter:
            yield current_word
            if save_delimiter:
                yield char
            current_word = ''
        else:
            current_word += char
    yield current_word


>>> list(split('I like to ride my bicycle', save_delimiter=True))
['I', ' ', 'like', ' ', 'to', ' ', 'ride', ' ', 'my', ' ', 'bicycle']
>>> 

【讨论】:

    【解决方案3】:

    我在@DYZ 的第一个答案的帮助下得到了它。谢谢!显然,我跳过了最后一个词,因为我需要在返回之前添加(下面)。

    words.append(current_word) 
    

    我的代码:

    def stringSplitter(string):
        words = []
        current_word = ""
        for char in string:
            if char == " ":
                words.append(current_word)
                current_word = ""
            else:
                current_word += char
        words.append(current_word)        
        return words
    

    【讨论】:

      最近更新 更多