Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String_Python 2.7 - Fatal编程技术网

Python 调用字符串的索引位置

Python 调用字符串的索引位置,python,string,python-2.7,Python,String,Python 2.7,因此,我正在编写一个小程序,作为从文件路径中提取名称的更大程序的一部分。所讨论的名称总是从文件路径中的同一点开始,因此我的推理是这样的,以获得我想要的名称 假设路径是这样的C:/Docs/Bob/blah/blah/blah/blah #cut the string at to the beginning of the name path = path[8:] #make a loop to iterate over the string for letter in path: if(l

因此,我正在编写一个小程序,作为从文件路径中提取名称的更大程序的一部分。所讨论的名称总是从文件路径中的同一点开始,因此我的推理是这样的,以获得我想要的名称

假设路径是这样的C:/Docs/Bob/blah/blah/blah/blah

#cut the string at to the beginning of the name
path = path[8:]
#make a loop to iterate over the string
for letter in path:
    if(letter == '/'):
        string_index = index

return path[:string_index]
我要找的是一种获取“索引”的方法


谢谢

不要这样做。改用
os.path
。例如:

>>> import os.path
>>> path = 'C:\\Docs\\Bob\\blah\\blah\\blah'
>>> base = 'C:\\Docs'
>>> os.path.relpath(path, base)
'Bob\\blah\\blah\\blah'
另外,使用
os.path
将确保您的代码可以在其他平台上工作,而不仅仅是Windows(假设基本路径设置正确)

如果您只想用“Bob”作为答案,那么您可能需要做如下操作

>>> import re
>>> # Windows supports both / and \
>>> if os.path.altsep:
...     sep=os.path.sep + os.path.altsep
... else:
...     sep=os.path.sep
...
>>> pseps = re.compile('[%s]' % re.escape(sep))
>>> pseps.split(os.path.relpath(path,base), 1)[0]
'Bob'

(遗憾的是,
os.path.split()
只能从最右边开始工作,因此我们不能在这里不递归地轻松使用它。)

阅读
枚举
帮助。您正在尝试获取哪个
/
的索引?有很多。字符串会自动剪切,所以它从Bob/blah开始。。。除了“鲍勃”,我想删掉一切