Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim specific leading and trailing characters from a string

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:

  1. Is this the best trim function for trimming specific characters in Python 3?
  2. Are there specific path functions for such operations in Python 3 so I don't have to set the delimiters manually?
like image 396
Roi Danton Avatar asked Feb 03 '17 14:02

Roi Danton


People also ask

How do you cut leading and trailing spaces from a string?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do you remove leading and trailing characters?

Trim() Trim() removes the leading and trailing occurrences of whitespaces from a string and returns a new string. Each leading and trailing trim operation is stopped when a character other than a whitespace is encountered.

How do you remove leading and trailing characters from a string in Java?

In the StringUtils class, we have the methods stripStart() and stripEnd(). They remove leading and trailing characters respectively.

How do you remove leading and trailing characters in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.


1 Answers

I believe strip is the pythonic way. It is usually the case when there is a builtin function.

There are a few builtin path manipulators available in the os library. You might want to use them if one of the manipulators is a match for your use case.

like image 65
pmuntima Avatar answered Sep 17 '22 08:09

pmuntima