Trim specific leading and trailing characters from a string
Question:
I have a string that contains a path
str = "/example/path/with/different/trailing/delimiter"
and I want to trim the leading and trailing /
and
. What is the best practice in Python 3?
Currently I’m using
trimmedPath = str.strip("/\")
# trimmedPath is "example/path/with/different/trailing/delimiter" as desired
Two questions:
- Is this the best trim function for trimming specific characters in Python 3?
- Are there specific path functions for such operations in Python 3 so I don’t have to set the delimiters manually?
Answers:
Example of strip()
in action; in this case, removing a leading plus sign:
In [1]: phone_number = "+14158889999"
In [2]: phone_number.strip('+')
Out[2]: '14158889999'
I have a string that contains a path
str = "/example/path/with/different/trailing/delimiter"
and I want to trim the leading and trailing /
and . What is the best practice in Python 3?
Currently I’m using
trimmedPath = str.strip("/\")
# trimmedPath is "example/path/with/different/trailing/delimiter" as desired
Two questions:
- Is this the best trim function for trimming specific characters in Python 3?
- Are there specific path functions for such operations in Python 3 so I don’t have to set the delimiters manually?
Example of strip()
in action; in this case, removing a leading plus sign:
In [1]: phone_number = "+14158889999"
In [2]: phone_number.strip('+')
Out[2]: '14158889999'