Friday, April 15, 2011

Is there a method in python that's like os.path.split for other delimiters?

I want to use something like this:

os.path.split("C:\\a\\b\\c")

With this kind of output:

('C:\a\b', 'c')


However I want it to work on other delimiters like this:

method ('a_b_c_d')

With this kind of output:

('a_b_c', 'd')

From stackoverflow
  • >>> 'a_b_c_d'.rsplit('_', 1)
    ['a_b_c', 'd']
    

    Help on built-in function rsplit:

    rsplit(...) S.rsplit([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator.

    S.Lott : +1: Quote the documentation.
  • string.split(separator)
    
    recursive : that produces ["a", "b", "c", "d"]

0 comments:

Post a Comment