Reputation: 590
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?
Upvotes: 0
Views: 189
Reputation: 1155
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'
Upvotes: 3
Reputation: 521
How does this look?
inputstring = 'dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn'
filename = os.path.basename(inputstring)
localname = 'local'
os.path.join(localname, filename)
Upvotes: 0
Reputation: 43494
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'
Upvotes: 0
Reputation: 82755
Use os
module
Ex:
import os
path = "dirA/dirB/a1ed4f3b-a046-4fbf-bb70-0774bd7bfcn"
print(os.path.join("locals", os.path.basename(path)))
Upvotes: 3