0

I have a large string with potentially many paths in it resembling this structure:

dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn

and I need to replace everything before the a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn part of the string with "local/" such that the result will look like this:

local/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn

The string could contain more than just dirA/dirB/ at the start of the string too.

How can I do this string manipulation in Python?

4 Answers 4

3

Using regular expressions, you can replace everything up to and including the last "/" with "locals/"

import re
s = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
re.sub(r'.*(\/.*)',r'local\1',s)

and you obtain:

'local/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'
Sign up to request clarification or add additional context in comments.

3 Comments

the char / doesn't need to be escaped
TYVM @Tomerikoo :)
I like the change but it's still escaped haha you can change (\/.*) to (/.*) in the first regex
3

Use os module

Ex:

import os


path = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
print(os.path.join("locals", os.path.basename(path)))

Comments

0

Another alternative is to split the string on "/" and then concatenate "locals/" with the last element of the resultant list.

s = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
print("locals/" + s.split("/")[-1])
#'locals/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'

Comments

0

How does this look?

inputstring = 'dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'
filename = os.path.basename(inputstring)
localname =  'local'
os.path.join(localname, filename)

2 Comments

Or just "local/" + os.path.basename(inputstring)
@Tomerikoo . . . true, but I believe os.path.join() will format it in a manner consistent with the operating system so it will work in any environment. Linux uses forward slashes and Windows uses backslashes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.