Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break string into list of characters in Python [duplicate]

Essentially I want to suck a line of text from a file, assign the characters to a list, and create a list of all the separate characters in a list -- a list of lists.

At the moment, I've tried this:

fO = open(filename, 'rU') fL = fO.readlines() 

That's all I've got. I don't quite know how to extract the single characters and assign them to a new list.

The line I get from the file will be something like:

fL = 'FHFF HHXH XXXX HFHX' 

I want to turn it into this list, with each single character on its own:

['F', 'H', 'F', 'F', 'H', ...] 
like image 507
FlexedCookie Avatar asked Mar 23 '12 02:03

FlexedCookie


People also ask

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

Use the list() class to split a string into a list of characters, e.g. my_list = list(my_str) . The list() class will convert the string into a list of characters.

How do you copy a string to a list in Python?

To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.

How do you split a string into multiple strings in Python?

In Python you can split a string with the split() method. It breaks up a string (based on the given separator) and returns a list of strings. To split a string, we use the method . split() .


2 Answers

You can do this using list:

new_list = list(fL) 

Be aware that any spaces in the line will be included in this list, to the best of my knowledge.

like image 81
Elliot Bonneville Avatar answered Nov 01 '22 15:11

Elliot Bonneville


I'm a bit late it seems to be, but...

a='hello' print list(a) # ['h','e','l','l', 'o'] 
like image 35
Oscar Avatar answered Nov 01 '22 14:11

Oscar