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?
CodePudding user response:
Use find()
twice:
firstspace = line.find(" ")
if firstspace != -1:
secondspace = line.find(" ", firstspace 1)
The second argument to str.find()
is the position to start searching from.
CodePudding user response:
If you want the last space, use rfind
or if you really want the last word, .rsplit()
for it
>>> "Coner John Smith".rfind(" ")
10
>>> "Coner John Smith".rsplit(" ", 1)[-1]
'Smith'
If you want the Nth space, you can repeatedly locate with .find()
, which can accept a start arg for where to begin finding!
source_text = "Coner John Smith"
N = 2
index = -1 # search from index 0
for _ in range(N):
index = source_text.find(" ", index 1)
# opportunity to discover if missing or `break` on last, etc.
CodePudding user response:
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.