xxxxxxxxxx
Use the lstrip() method
>>> name = ' Steve '
>>> name
' Steve '
>>> name = name.lstrip()
>>> name
'Steve '
xxxxxxxxxx
a = " yo! "
b = a.strip() # this will remove the white spaces that are leading and trailing
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
Use the strip() method
Example
>>> name = ' Steve '
>>> name
' Steve '
>>> name = name.strip()
>>> name
'Steve'
xxxxxxxxxx
import re
my_string = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)
print(output)
xxxxxxxxxx
text = " Example text with whitespace "
# Removing leading and trailing whitespace
trimmed_text = text.strip()
print(trimmed_text)