1

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]].

0

4 Answers 4

5

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'.

Sign up to request clarification or add additional context in comments.

Comments

4

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

3
>>> name = 'Peter Piper Picker'
>>> a = name.split()
>>> a[len(a)-1]
'Picker'

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.