Strip spaces/tabs/newlines - python
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'
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.
Use the re library
import remyString = "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