Search code examples
pythonlistreadlines

Break string into list of characters in Python


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', ...]

Solution

  • 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.