-1

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 (/)
2
  • Use pathlib's path. from pathlib import Path; p = Path(path); fds89 = p.stem; arc = p.parent.stem;. "fds89" will be "fds89gsa8asdfas0sgfsaajajgsf6shjksa6" and "arc" will be "arc-D41234" Commented Dec 1, 2022 at 16:53
  • @Shmack, just use fds, arc = p.parts[-2:] Commented Dec 1, 2022 at 17:20

1 Answer 1

0

You need to split the path like:

a = path.split('/')[-1] b = path.split('/')[-2] 
Sign up to request clarification or add additional context in comments.

1 Comment

.rsplit() with maxsplit suits slightly better. a, b = path.rsplit("/", 2)[-2:] or _, a, b = path.rsplit("/", 2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.