سؤال

There are two variables.

A variable drive was assigned a drive path (string). A variable filepath was assigned a complete path to a file (string).

drive = '/VOLUMES/TranSFER'
filepath = '/Volumes/transfer/Some Documents/The Doc.txt'

First I need to find if a string stored in a drive variable is in a string stored in filepath variable. If it is then I need to extract a string stored in drive variable from a string stored in a filepath variable without changing both variables characters case (no changing to lower or uppercase. The character case should stay the same).

So a final result should be:

result = '/Some Documents/The Doc.txt'

I could get it done with:

if drive.lower() in filepath.lower(): result = filepath.lower().split( drive.lower()  )

But approach like this messes up the letter case (everything is now lowercase) Please advise, thanks in advance!

EDITED LATER:

I coould be using my own approach. It appear IF portion of the statement

if drive.lower() in filepath.lower():

is case-sensitive. And drive in filepath will return False if case doesn't match. So it would make sense to lower()-case everything while comparing. But a .split() method splits beautiful regardless of the letter-cases:

if drive.lower() in filepath.lower(): result = filepath.split( drive  )
هل كانت مفيدة؟

المحلول

if filepath.lower().startswith(drive.lower() + '/'):
    result = filepath[len(drive)+1:]

نصائح أخرى

Using str.find:

>>> drive = '/VOLUMES/TranSFER'
>>> filepath = '/Volumes/transfer/Some Documents/The Doc.txt'
>>> i = filepath.lower().find(drive.lower())
>>> if i >= 0:
...     result = filepath[:i] + filepath[i+len(drive):]
...
>>> result
'/Some Documents/The Doc.txt'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top