The Python strip() function is very useful when working with strings. strip() removes a given character from the beginning and end of a string.
str = " 1234 "
print(str.strip())
#Output:
1234
When working with strings, the ability to easily be able to manipulate and change the values of those strings is valuable.
One such situation is if you have leading and trailing characters you want to get rid of.
The Python strip() strips a given character from the beginning and end of a string. By default, spaces are removed from the end of the string, but you can pass any character.
Below is an example showing you how to use strip() in Python to remove leading and trailing spaces.
str = " 1234 "
print(str.strip())
#Output:
1234
Removing Trailing Character from String in Python with rstrip() Function
If you have a trailing character and want to get rid of it without doing anything to the beginning of the string, you can use the Python rstrip() function.
rstrip(), or “right strip”, removes a given character from the end of a string if they exist. By default, spaces are removed from the end of the string, but you can pass any character.
Below is an example of how you can remove trailing zeros from a string using rstrip().
str = "12340000"
print(str.rstrip("0"))
#Output:
1234
Removing Leading Character from String in Python with lstrip() Function
If you have a leading character and want to get rid of it without doing anything to the beginning of the string, you can use the Python rstrip() function.
lstrip(), or “left strip”, removes a given character from the beginning of a string if they exist. By default, spaces are removed from the beginning of the string, but you can pass any character.
Below is an example of how you can remove leading zeros from a string using lstrip().
str = "00001234"
print(str.lstrip("0"))
#Output:
1234
Hopefully this article has been useful for you to learn how to the Python strip() function to remove leading and trailing characters in Python.