I'm doing a practice exercise where I input a string and the code must find the first number that appears, then print that number.
I have one loop to first check if there's even digits, and a second loop to find the end of that number. My problem is that the second loop doesn't know when to stop. Even if the number ends, it keeps going.
Here's all the relevant code I have:
s = str(input("Input a string: "))
# counter to find digit's index
i = 0
while i < len(s) and not s[i].isdigit():
i += 1
# counter to find end of number's index
j = i
if i < len(s) and s[i].isdigit:
# find end of number, if any
while j < len(s) and s[j].isdigit:
j += 1
# i and j now indicate the starting and ending index of the number
full_number = s[i:j]
If I input 'hello 123 world', then full_number should be '123', but it actually returns '123 world'. I have absolutely no clue why, since the second loop's condition should not be fulfilled by ' world'.
Any help would be appreciated
You have forgotten to call ()
on your isdigit()
. Therefore your code never checks if anything after i
is a digit, it just iterates and += 1
every element until it reaches len(s)
if i < len(s) and s[i].isdigit():
# find end of number, if any
while j < len(s) and s[j].isdigit():
j += 1