How to Strip Leading and Trailing Zeros from a String in Python?

Estimated read time 1 min read

To strip leading and trailing zeros from a string in Python, you can use the lstrip() and rstrip() functions with the character to be removed as an argument. Here is an example code snippet that removes leading and trailing zeros from a string:

string_with_zeros = "0001234000"

# Strip leading and trailing zeros
stripped_string = string_with_zeros.lstrip('0').rstrip('0') or '0'

print(stripped_string)  # Output: 1234

In this code, we define a string that contains leading and trailing zeros (string_with_zeros).

Next, we use the lstrip() function to remove all leading zeros from the string, and then use the rstrip() function to remove all trailing zeros from the string.

Finally, we use the or operator to ensure that if the stripped string is empty, the result is ‘0’.

Note that if the string contains only zeros, the or '0' statement at the end of the code will ensure that the result is ‘0’.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply