Kodeclik Blog
ABOUT
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
PROGRAMS
Computer Science Camps
Online CS Classes
Math Camps
Online Math Classes
Self Learning CS Courses
Coding Contest
POPULAR CLASSES
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
In your Python journey, you will encounter situations where you have a string denoting a number but which might contain extraneous leading zeros. For instance, you might have a string such as “00314” or “01234” and you desire to remove the leading zeros, so that we obtain “314” or “1234”. Here are five ways to remove leading zeros from a Python string.
We can write a vanilla for loop going through the string one character at a time and remove the leading zeros. For this purpose we create a variable to keep track of whether we are at the beginning of the string and once we cross the segment of leading zeros we recognize that we no longer need to remove leading zeros.
In the code below, mystring contains the original string with potentially leading zeros and newstring contains the modified string, with zeros removed. The variable beginning keeps track of whether we are at the beginning of the string. Note also that we use the pass statement because we have an empty block in our if..else statement.
The output is, as expected:
The above code can be made more succinct using Python’s string slicing operators in a while loop. For instance, consider the following code:
This will output as before:
The lstrip() method operates on a given string and returns a string with leading characters removed (and you can specify which leading characters you are interested in).
In the above code lstrip works on the mystring variable and removes leading characters where the leading character is specified to be 0.
This code outputs:
See how simple the code is? This is because somebody has done the hard work of writing the logic we need inside the lstrip() method.
In this method we write our own function that recursively calls itself to remove leading zeros. If there are no zeros it simply returns its input as the output.
In the above we use the startswith() method to check if the string has a leading zero. Note that this will only check if there is a first leading zero and will not be able to distinguish between one or two (or more) leading zeros. Thus, as soon as a leading zero is detected, we recursively call the function with the string from the second character. If no leading zero is detected, the given string is simply returned (the base case for the recursion).
If we use this function like so:
we will get:
The built-in int() function converts (casts) a string to an integer and str() converts (casts) an integer to a string. Implicitly int() helps remove leading zeros. Thus we can create a simple routine to remove leading zeros with:
This will output:
Note that this approach will only work for integers. It will not work if you have a decimal point in your number (but the earlier methods will work).
If we try:
we will get an error like:
However, the earlier methods will work for this case. To make this approach work with decimals, you simply have to update the int() function to use a float() instead. So the code becomes:
which yields:
What happens if we give a negative integer, such as “-0023”? Which methods work? We will leave it as an exercise for you to try them out and modify them as/if necessary.
If you enjoyed this blogpost, checkout our post on removing trailing zeros in a Python string. Learn also how to pad a Python string and how to remove the first character from a Python string.
Finally, learn about other casting functions such as the float() function in Python to convert strings to floating point values.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.
mystring = "000203"
beginning = True
newstring = ''
for x in mystring:
if (beginning and x=="0"):
pass
else:
newstring = newstring + x
beginning = False
print(newstring)
203
mystring = "000203"
while (mystring[0] == '0'):
mystring = mystring[1:]
print(mystring)
203
mystring = "000203"
print(mystring)
print(mystring.lstrip('0'))
000203
203
def remove_leading_zeros(s):
if s.startswith('0'):
return(remove_leading_zeros(s[1:]))
else:
return(s)
print("00203")
print(remove_leading_zeros("00203"))
00203
203
print("00203")
print(str(int("00203")))
00203
203
print("0020.3")
print(str(int("0020.3")))
0020.3
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(str(int("0020.3")))
ValueError: invalid literal for int() with base 10: '0020.3'
print("0020.3")
print(str(float("0020.3")))
0020.3
20.3