python remove whitespace from list code example

Example 1: remove all whitespace from string python

import re
s = '\n \t this is a string   with a lot of whitespace\t'
s = re.sub('\s+', '', s)

Example 2: trimming spaces in string python

a = "      yo!      "
b = a.strip() # this will remove the white spaces that are leading and trailing

Example 3: python remove spaces

string=' t e s t ' 
print(string.replace(' ',''))

Example 4: remove extra spaces python

>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'

Example 5: strip whitespace python

>>> s.strip()
'Hello  World   From Pankaj \t\n\r\tHi There'

Example 6: python string remove whitespace

' sss d ssd s'.replace(" ", "")
# output: 'sssdssds'