Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不改变大小写的情况下从另一个字符串中提取字符串_Python_Split_Lowercase - Fatal编程技术网

Python 如何在不改变大小写的情况下从另一个字符串中提取字符串

Python 如何在不改变大小写的情况下从另一个字符串中提取字符串,python,split,lowercase,Python,Split,Lowercase,有两个变量 为变量驱动器分配了驱动器路径(字符串)。 变量filepath被分配到文件(字符串)的完整路径 首先,我需要找出存储在驱动器变量中的字符串是否在存储在文件路径变量中的字符串中。 如果是,那么我需要从存储在文件路径变量中的字符串中提取存储在驱动器变量中的字符串,而不更改两个变量的大小写(不更改为小写或大写。字符大小写应保持不变) 因此,最终结果应该是: result='/Some Documents/Doc.txt' 我可以通过以下方式完成: if drive.lower() in f

有两个变量

为变量驱动器分配了驱动器路径(字符串)。 变量filepath被分配到文件(字符串)的完整路径

首先,我需要找出存储在驱动器变量中的字符串是否在存储在文件路径变量中的字符串中。 如果是,那么我需要从存储在文件路径变量中的字符串中提取存储在驱动器变量中的字符串,而不更改两个变量的大小写(不更改为小写或大写。字符大小写应保持不变)

因此,最终结果应该是:

result='/Some Documents/Doc.txt'

我可以通过以下方式完成:

if drive.lower() in filepath.lower(): result = filepath.lower().split( drive.lower()  )
但是这样的方法弄乱了字母的大小写(现在所有的字母都是小写的) 请提前告知,谢谢

稍后编辑: 我可以用我自己的方法。它出现在语句的

if drive.lower() in filepath.lower():
是区分大小写的。如果大小写不匹配,文件路径中的驱动器将返回False。 因此,在比较时降低()大小写是有意义的。但是.split()方法不管字母大小写都会拆分:

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

使用:


drive,filepath='/gotcha','/this/gotcha/bad'
@HughBothwell,谢谢你指出这一点。我更新了答案。
drive,filepath='/gotcha','/this/gotcha/bad'
@HughBothwell,谢谢你指出这一点。我更新了答案。
if drive.lower() in filepath.lower(): result = filepath.split( drive  )
if filepath.lower().startswith(drive.lower() + '/'):
    result = filepath[len(drive)+1:]
>>> 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'