Real quick question. If I have a string 'hi my name is bill' and I want to reduce this to a list of letters, with no whitespaces (eg ['h', 'i', 'm', 'y'] as opposed to ['hi', 'i', ' ' , 'm', 'y', ' ', 'n'...]), is there a really quick and tidy way to do this? Or should I say, what is the best way?

If I use:

s='hi my name is bill'
print list(s)

Spaces are not removed.

I've also thought to try:

ls=[letter for letter in s.split() if letter != ' ']  

This doesn't work because first of all, I can't seem to find the whitespace character for python, and also seems like it should have a builtin way.

What do you guys think?

Recommended Answers

All 4 Replies

>>> s='hi my name is bill'
>>> print ''.join(c for c in s if c.isalpha())
himynameisbill
>>> print [c for c in s if c.isalpha()]
['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'b', 'i', 'l', 'l']
>>> 

Thanks PyTony. This is definatley a good solution; however, I need to be able to include nonalphabetic characters like "\" and "-" in the outstring. How can I tell Python to recognize a single whitespace character? I've been looking for this online and can't seem to come across it!

I'm an idiot. I went back to the code and python does recognize a single blank space, I must have just made a typo when I first tested this. The following works:

s='hi my name is bill'
print [c for c in s if c != ' ']
>>> s = 'hi my name is bill'
>>> ''.join(s.split())
'himynameisbill'
>>> list(''.join(s.split()))
['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'b', 'i', 'l', 'l']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.