Strip spaces/tabs/newlines - python

237,651

Solution 1

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'

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!

Share:
237,651
bachurim09
Author by

bachurim09

Updated on October 01, 2020

Comments

  • bachurim09
    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
    jan about 7 years
    this also removes ';'
  • Jesuisme
    Jesuisme over 5 years
    This is a correction of the original answer given by @TheGr8Adakron, not a duplicate
  • Sajad Karim
    Sajad Karim almost 5 years
    Thanks for the solution - I think a minor correction is needed, it should be '+' instead of '*'.