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.

zmo
  • 23,731
  • 4
  • 53
  • 86
h4ck3d
  • 5,874
  • 15
  • 49
  • 73

5 Answers5

3

Using str.rfind and slice notation:

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

In [726]: t[t.rfind('/')+1:]
Out[726]: 'HelloWorld'
Community
  • 1
  • 1
zhangxaochen
  • 21,211
  • 8
  • 48
  • 73
  • what does `t[t.rfind('/')+1:]` exactly do ? – h4ck3d Feb 26 '14 at 09:33
  • 2
    @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”. – poke Feb 26 '14 at 09:38
  • `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 – zmo Feb 26 '14 at 09:38
2

You can use str.rpartition like this

data = "/jrfServer_domain/jrfServer_admin/HelloWorld"
print(data.rpartition("/")[-1])
# HelloWorld
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
1
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'
Tanveer Alam
  • 4,987
  • 3
  • 20
  • 41
0

You can use os.path.basename:

>>> import os
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> os.path.basename(s)
'HelloWorld'
flowfree
  • 16,008
  • 12
  • 48
  • 75
0
>>> s=r'/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'

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

fotocoder
  • 45
  • 3