def countDigitsFromPosUntilLetter(st, pos):
ret=0
try:
st=st[pos:]
except:
return 0
for i in st:
if i.isdigit():
ret+=1
else:
break
return ret
这个确实错了,应该只有在遇到letter或结尾才break,else换成elif i.isalpha()
def countDigitsFromPosUntilLetter(st, pos):
abs_len = len(st)
cnt = 0
if pos >= 0: #the pos can be both negative or positive.
if pos >= abs_len:
raise IndexError
elif abs(pos) > abs_len:
raise IndexError
if st:
for i in st[pos:]:
if i.isalpha():
break
if i.isdigit():
cnt += 1
return cnt
print(countDigitsFromPosUntilLetter('12abc!#456', 0))
print(countDigitsFromPosUntilLetter('12abc!#456', 1))
print(countDigitsFromPosUntilLetter('12abc!#456', 2))
print(countDigitsFromPosUntilLetter('12abc!#456', 0))
从所给的位置(pos)开始数字符串st中有多少个数字,直到遇到字母或者数到字符串尾为止,返回数到的数字个数。字符串可以包含字母,数字和特殊字符