[SOLVED] using .find to find the space in a line Python

Issue

im currently using this code

position= line.find(" ")

to help me find a position for example in the case of a name: Coner John Smith

how do i single out the smith, currently my line of code wont help because it positions itself on the first space it finds, how do rewrite the code to find the second space in a line?

Solution

The answer to your literal question is:

position= line.find(" ", line.find(" ") + 1)

What this does is find the first space in line, and then find the first space in line, starting the search on the position of the first space, plus one. Giving you the position of the second space.

But as @barmar points out, this is probably an example of an XY problem

Do you want the second space? Or the last space (e.g. ‘Mary Jo Suzy Smith’)?

Do you want the position of the space? Or are you really just after the last word in the string? Do you care about any interpunction following the last word in the string (e.g. ‘John Smith!’)

Every case has a slightly different better answer.

To get the last word, you could:

last_word = line.split(' ')[-1]

To find the last space, if you need it for something else:

last_space = line.rfind(' ')

Etc.

Answered By – Grismar

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *