Skip to main content

How to remove leading zeros from a string in Python

How to remove leading zeros from a string in Python.

Here's a detailed step-by-step tutorial on how to remove leading zeros from a string in Python:

Step 1: Start by defining a string variable that contains the input value with leading zeros.

input_str = '0001234'

Step 2: Use the lstrip() method to remove leading zeros from the string. The lstrip() method removes characters from the left side of the string until it encounters a non-zero digit.

output_str = input_str.lstrip('0')

Step 3: Print the output string to verify that the leading zeros have been removed.

print(output_str)

The output will be:

1234

Alternatively, you can use regular expressions to remove leading zeros from a string.

Step 1: Import the re module, which provides support for regular expressions.

import re

Step 2: Define a regular expression pattern that matches one or more leading zeros at the beginning of the string.

pattern = r'^0+'

Step 3: Use the re.sub() function to replace the matched pattern with an empty string.

output_str = re.sub(pattern, '', input_str)

Step 4: Print the output string to verify that the leading zeros have been removed.

print(output_str)

The output will be the same as before:

1234

That's it! You've successfully removed the leading zeros from a string in Python.