FlexedCookie FlexedCookie - 5 months ago 8
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:

fL = 'FHFF HHXH XXXX HFHX'


^^^ 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

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:
       chars.append(c)

or

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

or

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

chars would contain all of the characters in the file.