How Can I remove the whitespaces from the string “aaa bbb ccc ddd eee”?
Printable View
How Can I remove the whitespaces from the string “aaa bbb ccc ddd eee”?
I can think of two ways to do this.
Using join-
>>> s='aaa bbb ccc ddd eee'
>>> s1=''.join(s.split())
>>> s1
‘aaabbbcccdddeee’
Using a list comprehension-
>>> s='aaa bbb ccc ddd eee'
>>> s1=str(''.join(([i for i in s if i!=' '])))
>>> s1
‘aaabbbcccdddeee’
If you want to specifically remove spaces from a string s, then the simplest option would be:
If you want to remove whitespace in general, then aakashdata's first example would work, but a variation of aakashdata's second example to use a generator instead of a list comprehension and to check for whitespace instead of just a space might be better:Code:s.replace(' ', '')
Code:import string
''.join(c for c in s if c not in string.whitespace)