for 循环将字符串拆分为单词不包括最后一个单词



我应该写这段代码,所以它从字符串返回一个列表,我想这样做,而不重复到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']
[]

您不需要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']
[]

问题由两个阶段组成:左/右strip和一个split

下面的代码应该与原始代码最相似。


从注释中:使用一个扩展字符串,在末尾附加一个额外的空白。这将只修复最后一个单词问题。

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 == " "

相关内容

最新更新