get a field
python.list at tim.thechases.com
Mon Feb 15 19:28:25 CET 2010
> mierdatutis mi wrote:
>> I have this:
>> I would like to extract this: 691046.shtml
>> But is dynamically. Not always have the same lenght the string.
>>>> s = "http://server/path/to/file/file.shtml"
>>>> s.rfind("/") # finds rightmost "/"
>>>> s[s.rfind("/")+1:] # substring starting after "/"
If I didn't use os.path.basename(s) then I'd write this as
>>> "http://server/path/to/file/file.shtml".rsplit('/', 1)[-1]
>>> "".rsplit('/', 1)[-1]
>>> "file.html".rsplit('/', 1)[-1]
I don't know how much of a difference it makes, but I always
appreciate seeing how various people solve the same problem. I
tend to lean away from the find()/index() methods on strings
because I have to stop and think which one raises the exception
and which one returns -1 (and that it's -1 instead of 0) usually
dropping to a python shell and doing
to refresh my memory.
FWIW, Steve's solution and the os.path.basename() both produce
the same results with all 3 input values, so it's more a matter
of personal style preference. The basename() version has
slightly different results if you have Windows paths with
s = r'c:\path\to\file.txt'
but since you (OP) know that they should be URLs with
forward-slashes, it should be a non-issue.
More information about the Python-list