Reputation: 71
If I have a name = 'Peter Piper Picker'
and I want my function to selective isolate 'Picker', what would I have to do? I don't mean like name[12:]
, but like where it picks out where the last space before the end of the name is and starts substring-ing from there? I know index function has two additional parameters, but I don't know how they can be applied properly in this setting I was thinking name[' ', name.split(len(name.split()-1)), name[len(name)-1]]
.
Upvotes: 1
Views: 204
Reputation: 2190
You could use the split
method of str
.
name = 'Peter Piper Picker'
# name.split() will return a list ['Peter', 'Piper', 'Picker'], we need its last element
ret = name.split()[-1]
Then ret
is 'Picker'
.
Upvotes: 5
Reputation: 7418
The cryptic way:
>>> name[[i for i, c in enumerate(name) if c == ' '][-1]+1:]
'Picker'
[i for i, c in enumerate(name) if c == ' ']
- this will get you all the indexes where there is a space (' '
) in your string[i for i, c in enumerate(name) if c == ' '][-1]
- this will get you the index of the last space[i for i, c in enumerate(name) if c == ' '][-1]+1
- this one is the position where you desired name part startsAnd finally you slice your name
.
Upvotes: 1
Reputation: 8335
You could also do:
name = 'Peter Piper Picker'
name.rsplit(" ",1)[1]
'Picker'
When using rsplit
you will get the following output:
name.rsplit(" ",1)
['Peter Piper', 'Picker']
Process:
You are splitting from the right and you are splitting once using " " and getting the second element
Information:
For more on rsplit
look into rsplit official document
Upvotes: 4
Reputation: 4268
>>> name = 'Peter Piper Picker'
>>> a = name.split()
>>> a[len(a)-1]
'Picker'
Upvotes: 3