How to remove leading spaces in a string with python ?

September 22, 2021    /    Viewed: 295    /    Comments: 0    /    Edit


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.

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!