Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to array of words - Python

I want to create a function in Python, where input will be the String and input it into an array to be returned.

For example:

Input: "The dog is red"  
Output: "The", "dog", "is", "red"

I believe the algorithm should work, but nothing is returned. From what I can assume, the if statement is not detecting the space ( ").

The code is below:

string = input("Input here:")
def token(string):
    start = 0
    i = 0
    token_list = []
    for x in range(0, len(string)):
        if " " == string[i:i+1]:
            token_list = token_list + string[start:i+1]
            print string[start:i+1]
            start = i + 1
        i += 1
    return token_list 
like image 771
user287474 Avatar asked Jul 02 '26 20:07

user287474


1 Answers

You can simply split the string.

result=input.split(" ")

or

string = raw_input("Input here:")
def token(string):
    start = 0
    i = 0
    token_list = []
    for x in range(0, len(string)):
        if " " == string[i:i+1][0]:
            token_list.append(string[start:i+1])
            #print string[start:i+1]
            start = i + 1
        i += 1
    token_list.append(string[start:i+1])
    return token_list

print token(string)
like image 119
vks Avatar answered Jul 05 '26 09:07

vks