Q:

How to make my code detect end of string in python?

I'm trying to write code to split a sentence without it's punctuation. For example, if a user inputs "Hello, how are you?", I can split the sentence to ['hello','how','are','you']
userinput = str(raw_input("Enter your sentence: "))

def sentence_split(sentence):
    result = []
    current_word = ""
    for letter in sentence:
        if letter.isalnum(): 
            current_word += letter     
        else: ## this is a symbol or punctuation, e.g. reach end of a word
            if current_word: 
                result.append(current_word)
                current_word = "" ## reinitialise for creating a new word
    return result

print "Split of your sentence:", sentence_split(userinput)

so far my code works, but if i put a sentence without ending it with a punctuation, the last word won't show up in result, for example, if the input were "Hello, how are you", the result would be ['hello','how','are'], I guess it's because there's no punctuation to tell the code the string is ended, is there a way I can make the program detect it's the end of string? So that even if the input were "Hello, how are you", the result would still be ['hello','how','are','you'].

A:

I've not tried to adjust your algorithm myself, but I think the method below should achieve what you are after.
def sentence_split(sentence):
    new_sentence = sentence[:]
    for letter in sentence:
        if not letter.isalnum():
            new_sentence = new_sentence.replace(letter, ' ')
    return new_sentence.split()

Now with it running:
runfile(r'C:\Users\cat\test.py', wdir=r'C:\Users\cat')
['Hello', 'how', 'are', 'you']
Edit: Fixed a bug with initialisation of new_sentence.

