+3 votes
in Programming Languages by (73.8k points)

I want to convert a string into a list of characters and the list should not have space ('') as an element even if the string has space. What is the Pythonic way to do it?

E.g.

'hello world' should be converted to ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'], not to ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

1 Answer

+1 vote
by (40.5k points)
selected by
 
Best answer

You can use wrap() function of the module textwrap to convert a string into a list of characters in one line. It will also remove space from the list.

E.g.

>>> import textwrap
>>> str='hello world, how are you'
>>> textwrap.wrap(str, width=1)
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', ',', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u']

Another way is to use list() function, but it will keep space as an element of the list which you need to remove.

E.g.

>>> str='hello world'
>>> t=list(str)
>>> t
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> t.remove(' ')
>>> t
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']


...