繁体   English   中英

如何计算 Python 中字符串的数字、字母、空格?

[英]How to count digits, letters, spaces for a string in Python?

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

这是我到目前为止所拥有的:

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

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

这是另一种选择:

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

以下代码将任何非数字字符替换为 '',允许您使用函数 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

你不应该设置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
# 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)

这段代码有2个错误:

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

x = []

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

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

忽略“修订后的代码”可能正确或不正确的任何其他内容,导致您的问题中当前引用的错误的问题是由于您没有引用字符串而使用未定义的变量调用“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)以匹配当前行为,同时还使用更好的编码风格并明确返回值的类型(在本例中为元组)。

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  
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)
>>>

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

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

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)

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

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

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

输入 :

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM