Cease
Cease

Reputation: 1172

calling the indexed position of a string

so I'm writing a small program as part of something larger to pull a name out of a file path. The name in question is always going to start at the same spot in the file path, so my reasoning was something like this to get the name i wanted.

Say the Path was something like this C:/Docs/Bob/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]

what I am looking for is a way to get that "index"

Thanks!

Upvotes: 0

Views: 41

Answers (1)

al45tair
al45tair

Reputation: 4433

Don't do this. Use os.path instead. For instance:

>>> import os.path
>>> path = 'C:\\Docs\\Bob\\blah\\blah\\blah'
>>> base = 'C:\\Docs'
>>> os.path.relpath(path, base)
'Bob\\blah\\blah\\blah'

Also, using os.path will ensure that your code will work on other platforms, not just Windows (assuming the base path is set correctly).

If you just want 'Bob' as the answer, then you probably want to do something like

>>> 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'

(Sadly os.path.split() only works from the rightmost end, so we can't easily use it here without recursing.)

Upvotes: 1

Related Questions