Reputation: 3
Suppose we have two file paths
C:\User\JohnDoe\Desktop\Happy\Happy\Expression\Smile.exe
C:\User\JohnDoe\Desktop\Happy\Expression\Smile.exe
We need to extract file path after the last mention of Happy.
Desired string should be
..\Expression\Smile.exe
for both cases.
How do we achieve this using python?
I thought of using split function
a = 'C:\\User\\JohnDoe\\Desktop\\Happy\\Happy\\Expression\\Smile.exe'
b = 'C:\\User\\JohnDoe\\Desktop\\Happy\\Expression\\Smile.exe'
print( a.split("Happy"))
print('..'+b.split("Happy")[1])
Output
['C:\\User\\JohnDoe\\Desktop\\', '\\', '\\Expression\\Smile.exe']
..\Expression\Smile.exe
I know that the first print statement is incorrect. Is there any cleaner way of doing this?
Upvotes: 0
Views: 324
Reputation: 36510
You might use .rsplit
method which accepts maximal number of splits as 2nd argumet:
path1 = r"C:\User\JohnDoe\Desktop\Happy\Happy\Expression\Smile.exe"
path2 = r"C:\User\JohnDoe\Desktop\Happy\Expression\Smile.exe"
print(path1.rsplit("Happy",1)[-1])
print(path2.rsplit("Happy",1)[-1])
output
\Expression\Smile.exe
\Expression\Smile.exe
Upvotes: 1
Reputation: 446
Use the last element after the split:
a = 'C:\\User\\JohnDoe\\Desktop\\Happy\\Happy\\Expression\\Smile.exe'
print(a.split("Happy")[-1])
output:
\Expression\Smile.exe
Upvotes: 2