我正在编写一个函数,它接受一个字符串,并确定它是否为整数。你知道吗
在很大程度上,它运作良好。唯一的问题是当我在数字前面使用+或-时。我以为我在while循环中考虑到了这一点,但它似乎没有执行。这是我的密码:
def isInteger(sentence):
"""(str) -> bool
takes veriable sentence, which is a string, and returns true if it is
an integer
>>> isInteger('75931')
True
>>> isInteger('345L55')
False
"""
value = True #Assume the string is a digit
if len(sentence) > 0:
sentence = sentence.strip()
else:
value = False
if sentence[0] == '+' or sentence[0] == '-' or sentence[0].isdigit() == True:
count = 1
while count < len(sentence) and sentence[count].isdigit() == True:
if sentence.isdigit() == True:
count += 1
else:
value = False
break
else:
value = False
print(value) #test
return value
如果字符串以
+
或-
开头,则if
条件通过:但是,
while
的条件仍然失败,因为您正在使用sentence[0].isdigit()
进行测试。你知道吗一个简单的解决方法是在检查后跳过第一个字符:
while循环之后的检查导致值返回False,因为您正在检查整个句子。你知道吗
用这个代替?你知道吗
相关问题 更多 >
编程相关推荐