【问题标题】:How to count digits, letters, spaces for a string in Python?如何在 Python 中计算字符串的数字、字母、空格?
【发布时间】:2014-09-12 17:31:35
【问题描述】:

我正在尝试制作一个函数来检测字符串中有多少个数字、字母、空格和其他内容。

这是我目前所拥有的:

def count(x):
    length = len(x)
    digit = 0
    letters = 0
    space = 0
    other = 0
    for i in x:
        if x[i].isalpha():
            letters += 1
        elif x[i].isnumeric():
            digit += 1
        elif x[i].isspace():
            space += 1
        else:
            other += 1
    return number,word,space,other

但它不起作用:

>>> count(asdfkasdflasdfl222)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    count(asdfkasdflasdfl222)
NameError: name 'asdfkasdflasdfl222' is not defined

我的代码有什么问题,如何将其改进为更简单、更精确的解决方案?

【问题讨论】:

  • 您的代码做了哪些不该做的事情?它应该做什么?您的调查发现了差异的原因是什么?
  • ...这个问题作为错字都离题了(您错过了一对引号,请参阅this answer)(至少有一个MCVE...)|和ask many question at once(1:出了什么问题,2:如何改进)。问题2主要是基于意见的,更适合Code Review(14年有codereview吗?)|
  • 我认为这个问题被赞成的唯一原因是因为this answer(它甚至不能解决错误(问题1),并且重写代码以不再使用函数)可能会有所帮助对很多人。 ||| This question was linked to on Meta.

标签: python string counting


【解决方案1】:

这是另一个选择:

s = 'some string'

numbers = sum(c.isdigit() for c in s)
letters = sum(c.isalpha() for c in s)
spaces  = sum(c.isspace() for c in s)
others  = len(s) - numbers - letters - spaces

【讨论】:

  • @sundarnatarajСундар 这是一个权衡。当然,它在输入字符串上迭代了 3 次,但我相信这样更容易阅读。
  • +1 分离任务时解决方案更简洁。干得好!为了加快速度,请考虑像这样使用 itertools.imap()numbers = sum(imap(str.isdigit, s))。在初始调用之后,它将以 C 速度运行,无需纯 Python 步骤,也无需方法查找。
  • @ShubhamS.Naik True 被视为 1 用于求和
  • 谢谢@ÓscarLópez 我同意 True 被视为 1,但是我想知道 numbers = sum(c.isdigit() for c in s) 正在生成哪个可迭代?由于 sum(1) 返回如下: >>> sum(1) Traceback (最近一次调用最后一次): File "", line 1, in TypeError: 'int' object is not iterable
  • sum里面是一个生成器表达式,我只是去掉了周围的(),因为它们是多余的
【解决方案2】:

以下代码将任何非数字字符替换为 '',允许您使用函数 len 计算此类字符的数量。

import re
len(re.sub("[^0-9]", "", my_string))

按字母顺序:

import re
len(re.sub("[^a-zA-Z]", "", my_string))

更多信息 - https://docs.python.org/3/library/re.html

【讨论】:

    【解决方案3】:

    您不应该设置x = []。那就是为您输入的参数设置一个空列表。此外,使用python的for i in x语法如下:

    for i in x:
        if i.isalpha():
            letters+=1
        elif i.isnumeric():
            digit+=1
        elif i.isspace():
            space+=1
        else:
            other+=1
    

    【讨论】:

    • 缩进是正确的(复制到stackoverflow时出错)。我使用 x=[] 的原因是试图让 Python 知道 x 是一个列表。如果我删除 x=[],它会显示:>>> count(aasdfs1111xxx) Traceback(最近一次调用最后):文件“”,第 1 行,在 count(aasdfs1111xxx) NameError: name ' aasdfs1111xxx' 未定义
    【解决方案4】:
    
    # Write a Python program that accepts a string and calculate the number of digits 
    # andletters.
    
        stre =input("enter the string-->")
        countl = 0
        countn = 0
        counto = 0
        for i in stre:
            if i.isalpha():
                countl += 1
            elif i.isdigit():
                countn += 1
            else:
                counto += 1
        print("The number of letters are --", countl)
        print("The number of numbers are --", countn)
        print("The number of characters are --", counto)
    

    【讨论】:

      【解决方案5】:

      这段代码有2个错误:

      1) 你应该删除这一行,因为它会将 x 重新写入一个空列表:

      x = []
      

      2) 在第一个“if”语句中,您应该缩进“letter += 1”语句,如:

      if x[i].isalpha():
          letters += 1
      

      【讨论】:

      • 嗨,如果我删除了 x = [],我运行时会出错。它说我输入的字符串“未定义”。
      • 我通过注释掉 x = [] 来执行这段代码,它工作正常。代码中的另一个错误是您需要使用 isdigit 而不是 isnumberic。在这里,我假设通过在 x 参数中传递字符串来调用 count 函数。 Like : count ("1233AASD 43") 如果它不能解决你的问题,请告诉我。
      【解决方案6】:

      忽略您的“修订代码”可能正确或不正确的任何其他内容,导致您问题中当前引用的错误的问题是由于您没有引用未定义的变量调用“count”函数引起的字符串。

      • count(thisisastring222) 查找名为 thisisastring222 的变量以传递给名为 count 的函数。为此,您必须提前定义变量(例如使用thisisastring222 = "AStringWith1NumberInIt."),然后您的函数将使用存储在变量中的值的内容而不是变量的名称来执行您想要的操作。
      • count("thisisastring222") 将字符串“thisisastring222”硬编码到调用中,这意味着 count 函数将使用传递给它的确切字符串。

      要修复对函数的调用,只需在 asdfkasdflasdfl222 周围添加引号,将 count(asdfkasdflasdfl222) 更改为 count("asdfkasdflasdfl222")

      就实际问题“如何在 Python 中计算字符串的数字、字母、空格”而言,“修改后的代码”的其余部分一目了然,只是返回行没有返回与您相同的变量'已在其余代码中使用。 要修复它而不更改代码中的任何其他内容,请将 numberword 更改为 digitletters,将 return number,word,space,other 更改为 return digit,letters,space,other,或者更好的是 return (digit, letters, space, other) 以匹配当前行为,同时还使用更好的编码风格并明确返回什么类型的值(在本例中为元组)。

      【讨论】:

        【解决方案7】:
        sample = ("Python 3.2 is very easy") #sample string  
        letters = 0  # initiating the count of letters to 0
        numeric = 0  # initiating the count of numbers to 0
        
                for i in sample:  
                    if i.isdigit():      
                        numeric +=1      
                    elif i.isalpha():    
                        letters +=1    
                    else:    
                       pass  
        letters  
        numeric  
        

        【讨论】:

        • 欢迎来到 StackOverflow。您最好解释您的解决方案,而不仅仅是发布匿名代码。也许你应该阅读How do I write a good answer,尤其是当它说简洁是可以接受的,但更完整的解释更好
        【解决方案8】:
        def match_string(words):
            nums = 0
            letter = 0
            other = 0
            for i in words :
                if i.isalpha():
                    letter+=1
                elif i.isdigit():
                    nums+=1
                else:
                    other+=1
            return nums,letter,other
        
        x = match_string("Hello World")
        print(x)
        >>>
        (0, 10, 2)
        >>>
        

        【讨论】:

          【解决方案9】:

          这是你打电话的一个错误。您正在使用参数(asdfkasdflasdfl222) 调用代码,该参数被解释为变量。但是,您应该使用字符串 "asdfkasdflasdfl222" 调用它。

          【讨论】:

            【解决方案10】:

            计算字符串中的字母个数:

            def iinn():        # block for numeric strings
                  
               b=(input("Enter numeric letter string "))
            
               if b.isdigit():
                   print (f"you entered {b} numeric string" + "\n")
                        
               else:
                
                   letters = sum(c.isalpha() for c in b)
                   print (f"in the string {b} are {letters} alphabetic letters")
                   print("Try again...","\n")        
                
               while True:
                   iinn()
            

            一个数字字符串块将按相反的顺序排列:

            numbers = sum(c.isdigit() for c in b)
            

            【讨论】:

              【解决方案11】:

              如果您想要一个简单的解决方案,请使用列表推导,然后获取该列表的 len:

              len([ch for ch in text if ch.isdigit()])
              

              这可以以类似的方式应用于 isalpha()

              【讨论】:

                【解决方案12】:

                输入:

                1

                26

                sadw96aeafae4awdw2 wd100awd

                import re
                
                a=int(input())
                for i in range(a):
                    b=int(input())
                    c=input()
                
                    w=re.findall(r'\d',c)
                    x=re.findall(r'\d+',c)
                    y=re.findall(r'\s+',c)
                    z=re.findall(r'.',c)
                    print(len(x))
                    print(len(y))
                    print(len(z)-len(y)-len(w))
                

                输出:

                4

                1

                19

                四位数字分别是 96、4、2、100 空格数 = 1 字母数 = 19

                【讨论】:

                • 这实际上并没有回答问题。问题是计算数字、字母和空格的数量,而不是找出所有数字实例。
                猜你喜欢
                • 2014-07-17
                • 1970-01-01
                • 2012-01-11
                • 2019-12-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-12-01
                相关资源
                最近更新 更多