Extract a substring from a path

Question:

I would like to extract two parts of the string (path).
In particular, I would like to have the part a = "fds89gsa8asdfas0sgfsaajajgsf6shjksa6" and the part b = "arc-D41234".

path = "//users/ftac/tref/arc-D41234/fds89gsa8asdfas0sgfsaajajgsf6shjksa6"
a = path[-36:]
b = path[-47:-37]

I tried with slicing and was fine, the problem is that I have to repeat for various paths (in a for loop) and the part "fds89gsa8asdfas0sgfsaajajgsf6shjksa6" and also the part "//users/ftac/tref/" is not always with the same str length and with the same subfolder numbers.
The only thing is that I want to take the name of the last two subfolders.

Can someone help me, how can I solve this?

I think that the algorithm should be:

  • Take the str a from the last character until the first (from the end) forward slash (/)
  • Take the str b from the first (from the end) forward slash (/) until the second (from the end) forward slash (/)
Asked By: fabio taccaliti

||

Answers:

You need to split the path like:

a = path.split('/')[-1]
b = path.split('/')[-2]
Answered By: Orfeas Bourchas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.