[英]How to extract a string from another string wihout changing a characters case
有兩個變量。
為變量驅動器分配了驅動器路徑(字符串)。 變量filepath被分配了文件(字符串)的完整路徑。
drive = '/VOLUMES/TranSFER'
filepath = '/Volumes/transfer/Some Documents/The Doc.txt'
首先,我需要確定存儲在驅動器變量中的字符串是否在文件路徑變量中存儲的字符串中。 如果是這樣,我需要從文件路徑變量中存儲的字符串中提取驅動器變量中存儲的字符串,而不更改兩個變量的字符大小寫(不更改為小寫或大寫。字符大小寫應保持不變)。
因此,最終結果應為:
result = '/Some Documents/The Doc.txt'
我可以用以下方法完成它:
if drive.lower() in filepath.lower(): result = filepath.lower().split( drive.lower() )
但是這樣的方法會弄亂字母的大小寫(現在所有內容都是小寫的),請告知,謝謝!
我可能會使用自己的方法。 出現在語句的IF部分
if drive.lower() in filepath.lower():
區分大小寫。 如果大小寫不匹配,則文件路徑中的驅動器將返回False。 因此,在進行比較時,對所有內容進行小寫(大寫)是有意義的。 但是,無論字母大小寫如何,.split()方法都會分割優美的圖片:
if drive.lower() in filepath.lower(): result = filepath.split( drive )
if filepath.lower().startswith(drive.lower() + '/'):
result = filepath[len(drive)+1:]
使用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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.