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.
Asked
Active
Viewed 1,312 times
5 Answers
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
-
-
-
indeed, but the way I'm suggesting works whatever the `/` partitioned string is. – zmo Feb 26 '14 at 09:34
-
-
1@Droider `-1` means the least element in the result of `data.rpartition("/")`, `-2` is the last but one :) – thefourtheye Feb 26 '14 at 09:36
-
-
-
-
-
1
-
Getting this error : [junit] [exec] AttributeError: 'string' object has no attribute 'rpartition' – h4ck3d Feb 27 '14 at 12:50
-
-
-
-
-
1
>>> s = '/jrfServer_domain/jrfServer_admin/HelloWorld'
>>> s.split('/')[-1]
'HelloWorld'

Tanveer Alam
- 5,185
- 4
- 22
- 43
-
Nope, this will not be as efficient as the other methods, since it has to split the entire string based on `/` – thefourtheye Feb 26 '14 at 09:42
-
-
1
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