-
April 25th, 2019, 01:45 AM
#1
Remove Whitespaces from the string
How Can I remove the whitespaces from the string “aaa bbb ccc ddd eee”?
-
April 25th, 2019, 05:01 AM
#2
Re: Remove Whitespaces from the string
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’
-
May 19th, 2019, 08:58 AM
#3
Re: Remove Whitespaces from the string
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:
import string
''.join(c for c in s if c not in string.whitespace)
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|