I have a string say /jrfServer_domain/jrfServer_admin/HelloWorld , now all I want is HelloWorld . How can I extract it from such strings ? In this case my delimiter is / . I'm very new to python.
5 Answers
Using str.rfind and slice notation:
In [725]: t='/jrfServer_domain/jrfServer_admin/HelloWorld'
In [726]: t[t.rfind('/')+1:]
Out[726]: 'HelloWorld'
3 Comments
h4ck3d
what does
t[t.rfind('/')+1:] exactly do ?poke
@Droider
t.rfind('/') finds the right-most index of '/' within t. If that index was stored in k, the expression would be t[k+1:] that is a string slice and means “take everything from the index k+1 up to the end”.zmo
t.rfind('/') returns the index of the last / in the list, so the index of H from HelloWorld is the +1, and [foo:bar] is returning a sliceYou can use str.rpartition like this
data = "/jrfServer_domain/jrfServer_admin/HelloWorld"
print(data.rpartition("/")[-1])
# HelloWorld
16 Comments
zmo
print(data.rpartition("/")[-1]) would be smarterthefourtheye
@zmo Accessing the same element in two different ways :)
zmo
indeed, but the way I'm suggesting works whatever the
/ partitioned string is.thefourtheye
@Droider
-1 means the least element in the result of data.rpartition("/"), -2 is the last but one :)poke
No,
rpartition exists for all strings. But seriously, just try it! |
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'
3 Comments
thefourtheye
Nope, this will not be as efficient as the other methods, since it has to split the entire string based on
/Tanveer Alam
Yes sir I get that, I think "rfind" would be more efficient.
falsetru
s.rsplit('/', 1)[-1]You can use os.path.basename:
>>> import os
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> os.path.basename(s)
'HelloWorld'