0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.