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]].
Add a comment
|
4 Answers
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'.
Comments
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
Comments
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 starts
And finally you slice your name.