加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 返回/打印句子中的数字位数或错误消息

发布时间:2020-12-20 11:24:16 所属栏目:Python 来源:网络整理
导读:我是网站和 python的新手,所以我希望我能提供所有必需的信息.我已经搜索过这个问题但是没有一个解决方案似乎适合我. 我正在尝试创建一个函数来读取一些文本并返回它包含的数字量.例如: “它是2012”,应该返回“Text has 4 digits” 如果没有数字,则应返回不
我是网站和 python的新手,所以我希望我能提供所有必需的信息.我已经搜索过这个问题但是没有一个解决方案似乎适合我.

我正在尝试创建一个函数来读取一些文本并返回它包含的数字量.例如:

“它是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)窗口中,这就是我写这样的块的原因.

解决方法

我刚刚解决了你的代码问题:

def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit():
            sum += 1

    if sum:
        print("Text has","digit(s)")
    else:
        print ("Text does not contain digits")


CountNumbers(input("Write some text: "))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读