2

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 5

3

Using str.rfind and slice notation:

In [725]: t='/jrfServer_domain/jrfServer_admin/HelloWorld'

In [726]: t[t.rfind('/')+1:]
Out[726]: 'HelloWorld'
Sign up to request clarification or add additional context in comments.

3 Comments

what does t[t.rfind('/')+1:] exactly do ?
@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”.
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 slice
2

You can use str.rpartition like this

data = "/jrfServer_domain/jrfServer_admin/HelloWorld"
print(data.rpartition("/")[-1])
# HelloWorld

16 Comments

print(data.rpartition("/")[-1]) would be smarter
@zmo Accessing the same element in two different ways :)
indeed, but the way I'm suggesting works whatever the / partitioned string is.
@Droider -1 means the least element in the result of data.rpartition("/"), -2 is the last but one :)
No, rpartition exists for all strings. But seriously, just try it!
|
1
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'

3 Comments

Nope, this will not be as efficient as the other methods, since it has to split the entire string based on /
Yes sir I get that, I think "rfind" would be more efficient.
s.rsplit('/', 1)[-1]
0

You can use os.path.basename:

>>> import os
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> os.path.basename(s)
'HelloWorld'

Comments

0
>>> s=r'/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'

maybe you should update your delimiter in your question to "/"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.