0

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']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Does this answer your question? [How do I split a string into a list of words?](https://stackoverflow.com/questions/743806/how-do-i-split-a-string-into-a-list-of-words) – Joe Jul 23 '23 at 09:18
  • This code will only append the characters after discovering a whitespace (" ") In case a string is not ending with whitespace, it will not append the last substring. You need to append i to list after completion of for loop – Mahan Vyakti Jul 23 '23 at 09:18
  • 1
    `count` is a weird choice of variable name. – interjay Jul 23 '23 at 09:19
  • \**[Hello, World!](https://en.wikipedia.org/wiki/%22Hello,_World!%22_program)* – Peter Mortensen Jul 24 '23 at 06:57
  • You have a remaining `count` string at the end of the loop because there is no trailing space to trigger its addition to `a`. One way to fix it would be to add a space to `s` in the for loop: `for i in s+' ':` – Alain T. Jul 24 '23 at 15:11

2 Answers2

1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Edoardo Balducci
  • 332
  • 1
  • 10
0

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
eri
  • 3,133
  • 1
  • 23
  • 35