Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into a list?

I want my Python function to split a sentence (input) and store each word in a list. My current code splits the sentence, but does not store the words as a list. How do I do that?

def split_line(text):      # split the text     words = text.split()      # for each word in the line:     for word in words:          # print the word         print(words) 
like image 774
Thanx Avatar asked Apr 13 '09 12:04

Thanx


People also ask

How do I split one string in a list?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split text in a list in Python?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.

How do I convert a string to a list of strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


2 Answers

text.split() 

This should be enough to store each word in a list. words is already a list of the words from the sentence, so there is no need for the loop.

Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:

words.append(word) 

not

word.append(words) 
like image 107
nstehr Avatar answered Oct 24 '22 06:10

nstehr


Splits the string in text on any consecutive runs of whitespace.

words = text.split()       

Split the string in text on delimiter: ",".

words = text.split(",")    

The words variable will be a list and contain the words from text split on the delimiter.

like image 40
zalew Avatar answered Oct 24 '22 06:10

zalew