1

I'm trying to replicate the .split() string method. It works well but it doesn't include the last word.

def stringSplitter(string):
    words = []
    current_word = ""
    for x in range(len(string)): #problem is here
        if string[x] == " ":
            words.append(current_word)
            current_word = ""
        else:
            current_word += string[x]
    return words

Test 1: When sentence=I like to ride my bicycle, my code incorrectly outputs:

['I', 'like', 'to', 'ride', 'my']

The result I want is:

['I', 'like', 'to', 'ride', 'my', 'bicycle']
1
  • If you are using indexing in your python for loop, you're usually doing something wrong. Commented Jun 10, 2017 at 6:01

3 Answers 3

4

Add words.append(current_word) just before returning from the function. That's your "lost" word. Also, there is no need to use either range or any indexing. for x in string: iterates directly over the characters.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Finally, so this is what I'm missing.
2

Note this could be implemented more succinctly using a generator function - if you didn't mind deviating from the "real" str.split() function implementation a little bit:

>>> def split(string, delimiter=' '):
    current_word = ''
    for char in string:
        if char == delimiter:
            yield current_word
            current_word = ''
        else:
            current_word += char
    yield current_word


>>> list(split('I like to ride my bicycle'))
['I', 'like', 'to', 'ride', 'my', 'bicycle']
>>> 

You could even modify it to allow returning the delimiter as well:

>>> def split(string, delimiter=' ', save_delimiter=False):
    current_word = ''
    for char in string:
        if char == delimiter:
            yield current_word
            if save_delimiter:
                yield char
            current_word = ''
        else:
            current_word += char
    yield current_word


>>> list(split('I like to ride my bicycle', save_delimiter=True))
['I', ' ', 'like', ' ', 'to', ' ', 'ride', ' ', 'my', ' ', 'bicycle']
>>> 

Comments

1

I got it with the help of the first answer by @DYZ. Thank you! Apparently, I was skipping the last word because I need to add (below) before the return.

words.append(current_word) 

My Code:

def stringSplitter(string):
    words = []
    current_word = ""
    for char in string:
        if char == " ":
            words.append(current_word)
            current_word = ""
        else:
            current_word += char
    words.append(current_word)        
    return words

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.