python how to remove whitespace from string 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: delete spaces in string python

>>> s.replace(" ", "")

Example 3: how to remove spaces in string in python

sentence = '       hello  apple         '
sentence.strip()
>>> 'hello  apple'

Example 4: python convert remove spaces from beginning of string

## Remove the Starting Spaces in Python
 
string1="    This is Test String to strip leading space"
print (string1.lstrip())

Example 5: remove extra spaces python

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

Example 6: how to strip white space of text in python?

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'