英文:
Last word is not appending in the list
问题
以下是已更正的代码:
def splitstring(s):
a = []
count = ''
for i in s:
if i == ' ':
if count:
a.append(count)
count = ''
else:
count += i
if count:
a.append(count)
return a
# 输入 = 'Hello World'
# 期望输出 = ['Hello', 'World']
# 实际输出 = ['Hello', 'World']
这个更正后的代码会将字符串中的单词分割并添加到列表中,包括最后一个单词。
英文:
I wrote the code of returning the words in a string into a list. But the code is not appending the last word in the string. Here I tried to replicate the split() method for strings. What will be the corrected code?
def splitstring(s):
a = []
count = ''
for i in s:
if i == ' ':
a.append(count)
count = ''
else:
count += i
return a
# Input = 'Hello World'
# Expected output = ['Hello', 'World']
# Actual = ['Hello']
答案1
得分: 1
你目前的实现无法处理字符串中的最后一个单词,因为它只在遇到空格时将单词附加到列表中。
要解决这个问题,你可以这样做:
def splitstring(s):
a = []
count = ''
for i in s:
if i == ' ':
a.append(count)
count = ''
else:
count += i
if count: # 添加这个条件以处理最后一个单词
a.append(count)
return a
尽管如此,我建议你使用Python内置的函数。它们经过优化且可靠。
英文:
Your current implementation doesn't handle the last word in the string, because it only appends the word to the list when it encounters a space.
To fix this problem, you can do this:
def splitstring(s):
a = []
count = ''
for i in s:
if i == ' ':
a.append(count)
count = ''
else:
count += i
if count: # Add this condition to handle the last word
a.append(count)
return a
Though, I suggest you to use Python's built-in functions. They are well optimized and reliable.
答案2
得分: 0
你没有任何与 if i == ' ':
的第二个匹配项。
快速修复:
def splitstring(s):
a = []
count = ''
for i in s:
if i == ' ':
a.append(count)
count = ''
else:
count += i
a.append(count)
return a
英文:
You don't have any second match for if i == ' ':
.
Quick fix:
def splitstring(s):
a = []
count = ''
for i in s:
if i == ' ':
a.append(count)
count = ''
else:
count += i
a.append(count)
return a
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论