In Python, how should one extract the second-last

2019-06-24 01:03发布

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]

6条回答
何必那么认真
2楼-- · 2019-06-24 01:30

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'
查看更多
仙女界的扛把子
3楼-- · 2019-06-24 01:31

cross platform solution:

import os
'/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore'.split(os.path.sep)[-2]
查看更多
仙女界的扛把子
4楼-- · 2019-06-24 01:32
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']
>>> 
查看更多
【Aperson】
5楼-- · 2019-06-24 01:35

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'
查看更多
祖国的老花朵
6楼-- · 2019-06-24 01:47
'/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore'.split('/')[-2]
查看更多
smile是对你的礼貌
7楼-- · 2019-06-24 01:50
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'
查看更多
登录 后发表回答