Strip spaces/tabs/newlines - python


Question

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?

1
73
1/3/2015 12:56:32 AM

Use str.split([sep[, maxsplit]]) with no sep or sep=None:

From docs:

If sep is not specified or is None, 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'
105
10/25/2013 7:25:59 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon