python-3.x for循环将字符串拆分为单词不包括最后一个单词

qq24tv8q  于 2023-04-08  发布在  Python
关注(0)|答案(3)|浏览(122)

我应该写这段代码,让它从一个字符串返回一个列表,我不想重复list()或split()函数,但尝试写我自己的函数,模仿split(),但只使用空格分隔。
代码如下:

def mysplit(strng):
    res = []
    word = ""
    for i in range(len(strng)):
        if strng[i] != " ":
            word += strng[i]
        else:
            res.append(word)
            word = ""
        
    if len(res) > 0:
        return res
    else:
        return []
#These below are tests.
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

这是预期输出:

['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]

这就是我得到的

['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the']
['', '', '']
['', 'abc']
[]
41zrol4v

41zrol4v1#

它没有将最后一个单词追加到结果列表中,因为最后一个单词后面没有空格字符。要解决这个问题,您可以在循环后添加一个额外的检查,以便在最后一个单词不为空时将其追加到结果列表中。

def mysplit(strng):
    res = []
    word = ""
    for i in range(len(strng)):
        if strng[i] != " ":
            word += strng[i]
        else:
            if word:  # Add this check to avoid appending empty words
                res.append(word)
                word = ""

    if word:  # Add this check to append the last word if it's not empty
        res.append(word)
        
    return res

print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

结果:

['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]
2nc8po8w

2nc8po8w2#

你不需要使用 range(),因为你可以遍历源字符串而不用担心它的长度。类似这样:

def mysplit(s):
    words = ['']
    for c in s:
        if c == ' ':
            if words[-1]:
                words.append('')
        else:
            words[-1] += c
    return words if words[-1] else words[:-1]

print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

输出:

['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]
ep6jt1vc

ep6jt1vc3#

这个问题分为两个阶段:左/右 * 条带 * 和 * 分割 *。
在下面的代码是指最相似的原始之一。
来自评论:使用一个扩展字符串,在末尾附加一个额外白色。这将解决最后一个单词 * 的问题。

def mysplit(strng):
    strng_ = strng + " " # <- extended string
    res = []
    word = ""
    for i in range(len(strng_)):
        if strng_[i] != " ":
            word += strng_[i]
        else:
            res.append(word)
            word = ""
        
    return res

tests = "To be or not to be, that is the question", "  To be or not to be, that is the question   ", " "

for test in tests:
    print(mysplit(test))

这里有一个完整的解决问题的方法.它只需要一个额外的检查.

def mysplit(strng):
    strng_ = strng + " " # <- extended string
    res = []
    word = ""
    for i in range(len(strng_)):
        if strng_[i] != " ":
            word += strng_[i]
        else:
            # check empty word
            if word:
                res.append(word)
            word = ""
        
    return res

这里是另一个完整的解决方案,这是基于一个DIY的左/右条

def mysplit(text):
    # left-strip
    c = 0
    for char in text:
        if char == " ":
            c += 1
        else:
            break

    # right-strip
    # reversed string
    text_ = text[c:][::-1]
    c = 0
    for char in text_:
        if char == " ":
            c += 1
        else:
            break

    # striped string
    text_ = text_[c:][::-1]
    
    # check empty string
    if not text_:
        return []
    
    # DIY-split
    text_ += " " # <- extended string
    res = []
    word = ""
    for i in range(len(text_)):
        if text_[i] != " ":
            word += text_[i]
        else:
            res.append(word)
            word = ""
        
    return res

备注:str.isspace可代替str == " "

相关问题