我是该网站和 python 的新手,所以我希望我能提供所有必需的信息。我已经搜索过这个问题,但似乎没有一个解决方案对我有用。
我正在尝试创建一个函数来读取一些文本并返回它包含的数字数量。例如:
"It is 2012" , 应该返回 "Text has 4 digits"
如果没有数字,它应该返回不同的消息,例如:
"今天是星期一" ,应该返回 "文本不包含数字"
所以我写了这个:
def CountNumbers(txt):
sum = 0
for n in txt:
if n.isdigit() == False:
print ("Text does not contain digits")
else:
sum += 1
print("Text has", sum, "digit(s)")
txt = str(input("Write some text: "))
(CountNumbers(txt))
功能似乎没问题,但是打印结果错误,例如:
Write some text: 65
Text has 2 digit(s) #this is ok, but...
当我只输入文本时:
Write some text: sd
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 0 digit(s)
当我输入文本和数字(但首先输入文本)时:
Write some text: sd 564
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 3 digit(s)
我知道我的错误在于块,(我认为),但我还没有想出办法,因为当我使用返回时,它会在完成阅读文本之前停止。我已经尝试了大约 20 多种不同的东西,请帮助我!
谢谢 !!
PS 我需要它作为 .py 而不仅仅是在 IDLE (Python Shell) 窗口中工作,这就是为什么我要编写这样的块。