xxxxxxxxxx
>>> s.strip()
'Hello World From Pankaj \t\n\r\tHi There'
xxxxxxxxxx
import re
s = '\n \t this is a string with a lot of whitespace\t'
s = re.sub('\s+', '', s)
xxxxxxxxxx
' hello world! '.strip()
'hello world!'
' hello world! '.lstrip()
'hello world! '
' hello world! '.rstrip()
' hello world!'
xxxxxxxxxx
text = " Example text with whitespace "
# Removing leading and trailing whitespace
trimmed_text = text.strip()
print(trimmed_text)
xxxxxxxxxx
sentence = ' hello apple'
" ".join(sentence.split())
>>> 'hello apple'
xxxxxxxxxx
s = ' This is a sentence with whitespace. \n'
print('Strip leading whitespace: {}'.format(s.lstrip()))
print('Strip trailing whitespace: {}'.format(s.rstrip()))
print('Strip all whitespace: {}'.format(s.strip()))
# Output
# Strip leading whitespace: This is a sentence with whitespace.
# Strip trailing whitespace: This is a sentence with whitespace.
# Strip all whitespace: This is a sentence with whitespace.
xxxxxxxxxx
s1 = ' abc '
print(f'String =\'{s1}\'')
print(f'After Removing Leading Whitespaces String =\'{s1.lstrip()}\'')
print(f'After Removing Trailing Whitespaces String =\'{s1.rstrip()}\'')
print(f'After Trimming Whitespaces String =\'{s1.strip()}\'')
xxxxxxxxxx
Use the lstrip() method
>>> name = ' Steve '
>>> name
' Steve '
>>> name = name.lstrip()
>>> name
'Steve '