Search code examples
pythonstringpathsplitslash

In Python, how should one extract the second-last directory name in a path?


I have a string like the following:

/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore

How should I extract the "2.0.24" from this string? I'm not sure how to split the string using the slashes (in order to extract the second last element of the resultant list) and I'm not sure if this would be a good approach. What I have right now is the following:

"/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore".split("/RootCore")[0].split("AnalysisTop/")[1]

Solution

  • '/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore'.split('/')[-2]