Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into a list of characters in Python?

Tags:

python

split

str.split(//) does not seem to work like Ruby does. Is there a simple way of doing this without looping?

If I have s = "foobar", I would like to get l = ['f', 'o', 'o', 'b', 'a', 'r']

like image 508
Adrian Avatar asked Feb 12 '11 15:02

Adrian


People also ask

How do you split a string into a list in Python?

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 a string into multiple strings in Python?

Split String in Python. To split a String in Python with a delimiter, use split() function. split() function splits the string into substrings and returns them as an array.

How do I split a string into a list of words?

To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.

How do you split a string into characters?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


2 Answers

>>> s = "foobar" >>> list(s) ['f', 'o', 'o', 'b', 'a', 'r'] 

You need list

like image 133
user225312 Avatar answered Oct 09 '22 03:10

user225312


You take the string and pass it to list()

s = "mystring" l = list(s) print l 
like image 29
Senthil Kumaran Avatar answered Oct 09 '22 04:10

Senthil Kumaran