How can I remove leading zeros from a string in Python?
Ava W
ava w profile pic

To remove leading zeros from a string in Python, you can use various methods. Here's a detailed explanation of a few commonly used approaches: Using the lstrip() method: Thelstrip() method is a built-in string method that can be used to remove leading characters from a string. By specifying the characters to be removed as an argument tolstrip(), you can remove leading zeros.

1
2
3
4
5
6

my_string = "0001234"

result = my_string.lstrip("0")

print(result)

In this example,my_string.lstrip("0") removes leading zeros from the string"0001234". The resulting string is assigned to the variableresult, and it is printed without the leading zeros. Using regular expressions: If you want to remove all leading zeros from a string, regardless of their position, you can use regular expressions (re module) to perform the removal.

1
2
3
4
5
6
7
8

import re

my_string = "0001234"

result = re.sub(r'^0+', '', my_string)

print(result)

In this example,re.sub(r'^0+', '', my_string) uses the regular expression pattern'^0+' to match one or more leading zeros at the start of the string. There.sub() function replaces the matched pattern with an empty string, effectively removing the leading zeros. The resulting string is assigned to the variableresult and displayed. Using int() and str() conversion: Another approach is to convert the string to an integer using theint() function, and then convert it back to a string using thestr() function. This method effectively removes leading zeros as the integer conversion does not preserve leading zeros.

1
2
3
4
5
6

my_string = "0001234"

result = str(int(my_string))

print(result)

In this example,int(my_string) converts the string"0001234" to an integer, effectively removing the leading zeros. Then,str() converts the resulting integer back to a string, and the modified string is assigned to the variableresult and displayed. It's important to note that if the string contains only zeros, all methods mentioned above will return an empty string. If you want to retain a single zero in such cases, you can add an additional check to handle that scenario. Choose the method that best suits your needs based on the specific requirements and context of your program.