Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+5 votes

I tried name.find(" ")
but thats just for one space. how do you do it for many

asked in CSC201 Spring 2021 by (1 point)

2 Answers

+5 votes

Hmm... I guess I haven't given you enough spells for this one yet after all!

You can do another FIND call where you start looking at a specified index.

firstSpaceIndex = name.find(" ")
secondSpaceIndex = name.find(" ", firstSpaceIndex + 1)

Or you could use rfind() to find backward from the end (right side):

secondSpaceIndex = name.rfind(" ")

However, these approaches may fail if there are multiple spaces separating between the names...

BETTER APPROACH: You could solve this problem using the split method, which splits a string into a list of smaller strings based on a separator string, which we'll talk about in class tomorrow.

nameParts = name.split(" ")

and then nameParts will be a list containing the first, middle, and last names as separate strings. We can index lists similar to how we index strings...

firstName  = nameParts[0]
answered by (508 points)
edited by
+4 votes

I used:

" ".join(fullName.split())

And then find and rfind

answered by (1 point)