Examples of how to remove leading spaces in a string with python:
Create a string variable in python
Let's create a string variable in python with 3 spaces at the begining and 4 at the end (after !):
s = ' Hello World ! '
Note that:
type( s )
gives
str
and
len(s)
gives
20
Count the number of spaces in a string
To count the number of spaces in string s:
space_count = 0
for c in s:
if c.isspace(): space_count += 1
print(space_count)
gives here
9
Remove leading spaces in a string
Using lstrip()
To remove leading spaces in a string, a solution is to use str.lstrip():
s_new = s.lstrip()
returns then
Hello World !
and
len(s_new)
gives
17
Using strip()
Another solution is to use strip()
s_new = s.lstrip()
returns then
Hello World !
and
len(s_new)
gives
13
Note that strip() remove leading and backward whitespaces.