Strip spaces/tabs/newlines - python
Solution 1
Use str.split([sep[, maxsplit]])
with no sep
or sep=None
:
From docs:
If
sep
is not specified or isNone
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
Demo:
>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']
Use str.join
on the returned list to get this output:
>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'
Solution 2
If you want to remove multiple whitespace items and replace them with single spaces, the easiest way is with a regexp like this:
>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '
You can then remove the trailing space with .strip()
if you want to.
Solution 3
Use the re library
import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = re.sub(r"[\n\t\s]*", "", myString)
print myString
Output:
IwanttoRemoveallwhitespaces,newlinesandtabs
Solution 4
import re
mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)
Output : IwanttoRemoveallwhitespacesnewlinesandtabs
Solution 5
This will only remove the tab, newlines, spaces and nothing else.
import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
output = re.sub(r"[\n\t\s]*", "", myString)
OUTPUT:
IwantoRemoveallwhiespaces,newlinesandtabs
Good day!
bachurim09
Updated on October 01, 2020Comments
-
bachurim09 over 3 years
I am trying to remove all spaces/tabs/newlines in python 2.7 on Linux.
I wrote this, that should do the job:
myString="I want to Remove all white \t spaces, new lines \n and tabs \t" myString = myString.strip(' \n\t') print myString
output:
I want to Remove all white spaces, new lines and tabs
It seems like a simple thing to do, yet I am missing here something. Should I be importing something?
-
jan about 7 yearsthis also removes ';'
-
Jesuisme over 5 yearsThis is a correction of the original answer given by @TheGr8Adakron, not a duplicate
-
Sajad Karim almost 5 yearsThanks for the solution - I think a minor correction is needed, it should be '+' instead of '*'.