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
  • 24,463
  • 4
  • 54
  • 90
h4ck3d
  • 6,134
  • 15
  • 51
  • 74

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
  • 32,744
  • 15
  • 77
  • 108
  • 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
  • 233,700
  • 52
  • 457
  • 497
1
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
0

You can use os.path.basename:

>>> import os
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> os.path.basename(s)
'HelloWorld'
flowfree
  • 16,356
  • 12
  • 52
  • 76
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