FlexedCookie FlexedCookie - 1 year ago 70
Python Question

Break string into list of characters in Python

So what i want to do is essentially suck a line of txt from a .txt file, then assign the characters to a list, and then creat a list of all the separate characters in a list.

So a list of lists.

At the moment, I've tried:

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

and that's all im up to. I dont quite know how to extract the single characters and assign them to a new list.

I want to do something like:


^^^ so that being the line i got from the .txt file.

And then turn it into this:

['F', 'H', 'F', 'F', 'H' ...]

^^^ and that being the new list, with each single character on it's own.

Answer Source

Strings are iterable (just like a list).

I'm interpreting that you really want something like:

fd = open(filename,'rU')
chars = []
for line in fd:
   for c in line:


fd = open(filename, 'rU')
chars = []
for line in fd:


chars = []
with open(filename, 'rU') as fd:
    map(chars.extend, fd)

chars would contain all of the characters in the file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download