在我的在线 PCAP 学习课程中,提出了这个问题:
您已经知道 split() 是如何工作的。现在我们希望你证明这一点。
您的任务是编写自己的函数,其行为几乎与原始 split() 方法完全相同,即:
给出的骨架是:
def mysplit(strng):
#
# put your code here
#
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']
[ ]
这是我想出的代码:
def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
else:
B.append(A)
A = ""
return(B)
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']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the']
['', '', '']
['', 'abc']
[]
非常感谢任何帮助!!
两个问题:
B
,因为只有在遇到空格时才会附加,并且字符串末尾没有空格。所以你需要附加最后一个词。A
附加到结果中。如果不为空,您应该只附加 A
。def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
elif A != "":
B.append(A)
A = ""
# Append last word
if A != "":
B.append(A)
return(B)
查看完最后一个字符后,没有额外的
" "
使您 append
成为您找到的最后一个单词,因此不会添加最后一个单词(“问题”)。
解决此问题的一种方法是在
for
循环之后添加另一个检查,看看是否需要添加最后一个单词。
您需要对代码进行一些小更改。仅当您找到空格字符时,您才将字符串添加到列表中。所以在字符串的末尾你不会找到要添加的空格字符。
def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
else:
B.append(A)
A = ""
B.append(A) # Add A when string is completed
return(B)
或者您可以维护相同的代码,但只需在获取参数时更改输入字符串
strng = strng + ' '
还注意到您没有考虑字符串中多个空格的情况。
假设你的字符串是
X Y
。您循环播放strng
。当您遇到 " "
时,您会将 X
添加到列表中。然后迭代 Y
并且 A
变成 Y
。然后循环终止。因此,Y
从未添加到列表中。
要解决此问题,循环结束后,只需检查
A
是否包含有效(非空)字符串。如果有,请追加。如果字符串的最后一个字符是空格,则在这种情况下,循环终止后 A
将保留空字符串,并且不会将其添加到列表中。
对于另一个问题,
" abc "
或" "
,在追加到列表之前 - 您可能需要检查A
是否为非空字符串。
试试这个 -
def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
else:
if A: # Check A is indeed a valid string
B.append(A)
A = ""
# After iteration is over check A contains a valid string. If so append
if A:
B.append(A)
return(B)
查看代码中的注释区域
def mysplit(strng):
word = ""
result = []
if type(strng) != str:
return(result)
else:
for i in strng:
if i.isspace() == False:
word+=i
else:
if word != "":
result.append(word)
word = ""
if word.isspace()== False:
if word != "":
result.append(word)
return(result)
最后一个 if word != "": 负责消除其中包含 "" 的列表。