How can I remove leading and trailing zeros from a string in Python?
Antek N
antek n profile pic

To remove leading and trailing zeros from a string in Python, you can use the built-instrip() method along with thelstrip() andrstrip() methods. These methods allow you to remove specific characters from the beginning and end of a string. Here's an example of how you can remove leading and trailing zeros from a string:

1
2
3
4
5
6
7
8
9
10

def remove_zeros(string):
    stripped_string = string.lstrip('0')  # Remove leading zeros
    stripped_string = stripped_string.rstrip('0')  # Remove trailing zeros
    return stripped_string

# Usage:
input_string = input("Enter a string with leading and trailing zeros: ")
result = remove_zeros(input_string)
print("Result:", result)

In the above code, theremove_zeros() function takes astring parameter. It uses thelstrip() method with the argument'0' to remove leading zeros from the string. Thelstrip() method scans the string from the left and removes any occurrences of the specified characters. Next, the function uses therstrip() method with the argument'0' to remove trailing zeros from the updated string. Therstrip() method scans the string from the right and removes any occurrences of the specified characters. Finally, the function returns the resulting stripped string. You can use theremove_zeros() function by passing a string as an argument. It will remove any leading and trailing zeros from the string and return the updated string. The updated string is then printed as the result. For example, if you input the string'000123000', the function will remove the leading and trailing zeros and return'123'. Keep in mind that if the input string contains characters other than zeros at the beginning or end, they will be retained in the resulting string. If you want to remove any leading or trailing characters, not just zeros, you can modify thelstrip() andrstrip() arguments accordingly. Additionally, if you only want to remove leading or trailing zeros (not both), you can choose to use eitherlstrip('0') orrstrip('0') instead of both, depending on your specific requirements.