算法在字符串中搜索数字,但在搜索结束后继续搜索(python 3.8)

算法在字符串中搜索数字,但在搜索结束后继续搜索(python 3.8),python,string,algorithm,loops,linear-search,Python,String,Algorithm,Loops,Linear Search,我正在做一个练习,输入一个字符串,代码必须找到出现的第一个数字,然后打印该数字 我有一个循环首先检查是否有偶数,第二个循环找到那个数字的结尾。我的问题是,第二个循环不知道何时停止。即使数字结束了,它也会继续 以下是我拥有的所有相关代码: 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 #

我正在做一个练习,输入一个字符串,代码必须找到出现的第一个数字,然后打印该数字

我有一个循环首先检查是否有偶数,第二个循环找到那个数字的结尾。我的问题是,第二个循环不知道何时停止。即使数字结束了,它也会继续

以下是我拥有的所有相关代码:

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]
s=str(输入(“输入字符串:”)
#计数器以查找数字的索引
i=0
而i
如果我输入'hello 123 world',那么完整的数字应该是'123',但它实际上返回'123 world'。我完全不知道为什么,因为第二个循环的条件不应该由“世界”来满足


如果您忘记在
isdigit()
上调用
()
,我们将不胜感激。因此,您的代码从不检查
i
之后的任何内容是否是数字,它只是迭代
+=1
每个元素,直到它到达
len(s)

如果i
根据您的情况,您正在检查
s[i]。isdigit
s[j]。isdigit
而不是
s[i]。isdigit()
s[j]。isdigit()

isdigit
是一个函数,必须调用它才能验证值

if i < len(s) and s[i].isdigit():
    # find end of number, if any
    while j < len(s) and s[j].isdigit():
        j += 1