9

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]
d3pd
  • 7,935
  • 24
  • 76
  • 127

6 Answers6

12

You can also do:

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

results in

'2.0.24'
AlG
  • 14,697
  • 4
  • 41
  • 54
9
'/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore'.split('/')[-2]
Slam
  • 8,112
  • 1
  • 36
  • 44
5

cross platform solution:

import os
'your/path'.split(os.path.sep)[-2]
Daniel Braun
  • 2,452
  • 27
  • 25
3

Just split according to the / symbol then print the second index from the last.

>>> x = "/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore"
>>> y = x.split('/')
>>> y[-2]
'2.0.24'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    So what if the string has more than 2 strings at the end? split('/')[-2] will fail – GLHF Feb 05 '15 at 15:59
-1
path = "/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore"
path_dirs = path.split("/")

>>>> path_dirs
>>>> ['', 'cvmfs', 'atlas.cern.ch', 'repo', 'sw', 'ASG', 'AnalysisTop', '2.0.24', 'RootCore']

>>>> print path_dirs[-2]
>>>> '2.0.24'
ZdaR
  • 22,343
  • 7
  • 66
  • 87
-2
import re

str1 = "/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore"
t = re.findall("[0-9][.]*",str1)
print ("".join(t))

You can use regex-findall method. t returns a list, so using join().

Output;

>>> 
2.0.24
>>> 

# print (t)
>>> 
['2.', '0.', '2', '4']
>>> 
GLHF
  • 3,835
  • 10
  • 38
  • 83
  • 1
    This is not the best solution. It might work in this case but not generic. what if you have /aaa/bbb/11/a/13/ ... – Bhanu Kaushik Feb 05 '15 at 15:58
  • So what if the string has more than 2 strings at the end? `split('/')[-2]` will fail. Dots are not change probably, so it's the best one I guess. – GLHF Feb 05 '15 at 15:59