Break string into list of characters in Python [duplicate]

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.


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

a='hello'
print list(a)
# ['h','e','l','l', 'o']

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.


python >= 3.5

Version 3.5 onwards allows the use of PEP 448 - Extended Unpacking Generalizations:

>>> string = 'hello'
>>> [*string]
['h', 'e', 'l', 'l', 'o']

This is a specification of the language syntax, so it is faster than calling list:

>>> from timeit import timeit
>>> timeit("list('hello')")
0.3042821969866054
>>> timeit("[*'hello']")
0.1582647830073256

So to add the string hello to a list as individual characters, try this:

newlist = []
newlist[:0] = 'hello'
print (newlist)

  ['h','e','l','l','o']

However, it is easier to do this:

splitlist = list(newlist)
print (splitlist)