found = False
position = 0
while not found and position < len(inputString):
if inputString[position].isdigit():
found = True
else:
position += 1
if found:
print('first digit is at position', position)
else:
print('There are no digits in the string')
这是我发现的一个简单程序,用于查找输入字符串中的第一个数字。我无法理解的事情是......
if inputString[position].isdigit(): found = True
这个表达式究竟说明了什么,特别是inputString[position]
部分。我们是否在寻找第一个数字的位置/索引值,然后将循环分解为下面的打印语句?
我们是否在寻找第一个数字的位置/索引值,然后将循环分解为下面的打印语句?
是的,这是真的。它会中断,因为一旦找到一个数字,在下一次迭代while not found
条件中就会给出while False
和中断while
循环。值得注意的是and
短路,因此甚至不评估第二个条件。
如果未找到数字,则position
递增直至等于len(inputString)
,此时while
循环会通过第二个条件(即 )中断position < len(inputString)
。
编写while
循环的一种更 Pythonic / 惯用的方法是通过for
循环和enumerate
:
for idx, val in enumerate(inputString, 1):
if val.isdigit():
position = idx
break
else:
position = 0
if position:
print('first digit is at position', position)
else:
print('There are no digits in the string')
注意,在这个解决方案中,由于我们从 1 开始计数,我们可以利用这样一个事实,如果找到一个数字,它必须是“Truthy”,即非零。因此,我们不需要额外的found
变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句