python whileloop的一个bug,我解决不了
Thisfunctionshouldcounthowmanydigitsthereareintheinputstringst,startingtocountfrompos...
This function should count how many digits there are in the input string st, starting to count from position pos (counting the character in pos if it is a digit) and advancing one position at a time until encountering a letter or until reaching the end of the string. The string may contain letters, digits and also special characters. If pos is not a valid position in the string, the function should return 0.
For example:
countDigitsFromPosUntilLetter('12abc!#456', 0) should return 2
countDigitsFromPosUntilLetter('12abc!#456', 1) should return 1
countDigitsFromPosUntilLetter('12abc!#456', 2) should return 0
以下是我的程序:
num=0
i=0
while (i>=pos) and (i<=len(st))and(st[i].isdigit()==True):
num=num+1
i=i+ 1
return num 展开
For example:
countDigitsFromPosUntilLetter('12abc!#456', 0) should return 2
countDigitsFromPosUntilLetter('12abc!#456', 1) should return 1
countDigitsFromPosUntilLetter('12abc!#456', 2) should return 0
以下是我的程序:
num=0
i=0
while (i>=pos) and (i<=len(st))and(st[i].isdigit()==True):
num=num+1
i=i+ 1
return num 展开
2个回答
展开全部
#!/usr/bin/python
# encoding: utf-8
def countDigitsFromPosUntilLetter(st, pos):
"""This function should count how many digits there are in the input string st,
starting to count from position pos (counting the character in pos if it is a digit)
and advancing one position at a time until encountering a letter or until reaching
the end of the string. The string may contain letters, digits and also special
characters. If pos is not a valid position in the string, the function should return 0.
"""
if pos >= len(st):
return 0
for i, ch in enumerate(list(st)[pos:]):
if not ch.isdigit():
break
return i
print countDigitsFromPosUntilLetter('12abc!#456', 0) # should return 2
print countDigitsFromPosUntilLetter('12abc!#456', 1) # should return 1
print countDigitsFromPosUntilLetter('12abc!#456', 2) # should return 0
or usage while-loop:
#!/usr/bin/python
# encoding: utf-8
def countDigitsFromPosUntilLetter(st, pos):
"""This function should count how many digits there are in the input string st,
starting to count from position pos (counting the character in pos if it is a digit)
and advancing one position at a time until encountering a letter or until reaching
the end of the string. The string may contain letters, digits and also special
characters. If pos is not a valid position in the string, the function should return 0.
"""
if pos >= len(st):
return 0
cnt = 0
while pos < len(st) and st[pos].isdigit():
pos += 1
cnt += 1
return cnt
print countDigitsFromPosUntilLetter('12abc!#456', 0) # should return 2
print countDigitsFromPosUntilLetter('12abc!#456', 1) # should return 1
print countDigitsFromPosUntilLetter('12abc!#456', 2) # should return 0
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询