h4ck3d
h4ck3d

Reputation: 6364

Find substring from end to index of a delimiter in PYTHON

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.

Upvotes: 2

Views: 1522

Answers (5)

zhangxaochen
zhangxaochen

Reputation: 34027

Using str.rfind and slice notation:

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

In [726]: t[t.rfind('/')+1:]
Out[726]: 'HelloWorld'

Upvotes: 3

fotocoder
fotocoder

Reputation: 45

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

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

Upvotes: 0

flowfree
flowfree

Reputation: 16462

You can use os.path.basename:

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

Upvotes: 0

Tanveer Alam
Tanveer Alam

Reputation: 5275

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

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239573

You can use str.rpartition like this

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

Upvotes: 2

Related Questions