1

I have two filepath as strings

string1 = r"C:\Users\Admin"  
string2= "C:\Users\Admin\Context1\Context2\filepath.dat"

How can I get the difference as "Context1\Context2\filepath.dat"

As of now I am iterating string1 by characters and comparing with string2 when it fails I am returning string2[index:]

there should be something easier pythonic way to do this. Or point me to the documentation. Please see me as novice in python. Any help is much appreciated

3
  • Is it just a coincidence that these strings happen to be file paths, or are you asking specifically how to get a relative file path from two absolute file paths?
    – Aran-Fey
    Commented Oct 3, 2017 at 14:25
  • what if the 1st string is string1 = 'C:\\Users\\Admin\\filepath.dat' Commented Oct 3, 2017 at 14:32
  • @rawing, All my inputs are going to be filepaths. But I am getting as string in the function where I do changes. Also In my case string1 is always going to be ancestral root of string2. Commented Oct 3, 2017 at 14:35

2 Answers 2

3

As simple as replacing the string1 with empty string in string2

string2.replace(string1,"")
0
1

Also In my case string1 is always going to be ancestral root of string2

string2[len(string1)+1:]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.