【发布时间】:2012-12-04 23:46:02
【问题描述】:
我是该网站和 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)
我知道我的错误在于块,(我认为),但我还没有想出办法,因为当我使用 return 时,它会在完成阅读文本之前停止。我已经尝试了大约 20 多种不同的方法,请帮助我!
谢谢!!
附:我需要它作为 .py 而不仅仅是在 IDLE (Python Shell) 窗口中工作,这就是我编写这样的块的原因。
【问题讨论】:
-
+1 表示简短的自包含代码和示例输入/输出。多个样品,甚至!喜欢它。
-
请记住,根据 Python 的命名约定,您的函数应命名为
count_numbers()而不是CountNumbers。 -
另外,你不应该将变量命名为
sum,因为这是一个内置函数的名称。 -
非常感谢你们!...我知道我很接近...这 python 的东西对我来说真的很复杂哈哈哈...谢谢!
-
是的,我不知道,因为我实际上是在用西班牙语编写代码,所以当我在这里翻译代码来询问它时,变量 suma(西班牙语为 sum)变成了 sum,直到在那之后我才意识到 sum 也是一个函数......它仍然有效,但我还是改变了它:P
标签: python string return message digits