Count number of leading spaces in a string in Python
In this blog, we are going to see how we can find the number of leading spaces in a string in Python.
What are leading spaces?
Leading spaces refer to the number of spaces that are there before your actual string begins.
Ex: Let there be a string s = ” Hello “. Here there are 4 spaces that are present there before the actual content of my string.
These spaces are known as leading spaces.
Why do we care about counting or removing these leading spaces?
Well in today’s computers it’s not really a necessity or a requirement for that matter to count these leading spaces, but in the earlier computers, it was a huge cause of chaos.
Ex: If you tested code that demanded an input and you accidentally add some leading spaces to your input, it could lead to a whole bunch of junk values to be printed.
This can also be seen when you are creating a password and add some leading spaces to your password as it can cause your data to be stored in the database in a different way.
Counting the leading spaces of a string in Python
To count the number of leading spaces in Python we have a really handy function called lstrip(). It gives us the output string by removing all the leading spaces present in our string. It also helps in removing defined function arguments present as leading characters in the string.
Syntax: string.lstrip(characters) Parameters: characters - a set of leading character that are to be removed Returns a copy of the string wth all the leading charechters stripped
Now that we have a string with leading spaces and a string without leading spaces all we have to do is subtract the length of both the strings and we get a count of the number of leading spaces in the string.
#Python program to count the leading characters #lstrip() method used in this code s = " CodeSpeedy " #Now using the code logic discussed earlier print(len(s) - len(s.lstrip())
(as there are 4 spaces before CodeSpeedy)
Also read: How to Use lstrip Method in Python