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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24878174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:24:15  来源:igfitidea点击:

How to count digits, letters, spaces for a string in Python

python

提问by ray

I am trying to make a function to detect how many digits,letter,spaces, and others for a string. Do you know what's wrong with my code? and can I improve my code to be more simple and precise?

我正在尝试创建一个函数来检测一个字符串有多少个数字、字母、空格等。你知道我的代码有什么问题吗?我可以改进我的代码以使其更简单和精确吗?

thanks! (here is the revised code)

谢谢!(这里是修改后的代码)

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

it showed this error:

它显示了这个错误:

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

回答by sshashank124

You shouldn't be setting x = []. That is setting an empty list to your inputted parameter. Furthermore, use python's for i in xsyntax as follows:

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

回答by Abhishek Mittal

There are 2 errors is this code:

这段代码有2个错误:

1) You should remove this line, as it will reqrite x to an empty list:

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

x = []

2) In the first "if" statement, you should indent the "letter += 1" statement, like:

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

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

回答by óscar López

Here's another option:

这是另一种选择:

s = 'some string'

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

回答by 3D1T0R

Ignoring anything else that may or may not be correct with your "revised code", the issue causing the error currently quoted in your question is caused by calling the "count" function with an undefined variable because your didn't quote the string.

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

  • count(thisisastring222)looks for a variable called thisisastring222 to pass to the function called count. For this to work you would have to have defined the variable earlier (e.g. with thisisastring222 = "AStringWith1NumberInIt.") then your function will do what you want with the contents of the value stored in the variable, not the name of the variable.
  • count("thisisastring222")hardcodes the string "thisisastring222" into the call, meaning that the count function will work with the exact string passed to it.
  • count(thisisastring222)查找名为 thisisastring222 的变量以传递给名为 count 的函数。为此,您必须更早地定义变量(例如 with thisisastring222 = "AStringWith1NumberInIt."),然后您的函数将对存储在变量中的值的内容执行您想要的操作,而不是变量的名称。
  • count("thisisastring222")将字符串“thisisastring222”硬编码到调用中,这意味着 count 函数将使用传递给它的确切字符串。

To fix your call to your function, just add quotes around asdfkasdflasdfl222changing count(asdfkasdflasdfl222)to count("asdfkasdflasdfl222").

要修复对函数的调用,只需在asdfkasdflasdfl222更改count(asdfkasdflasdfl222)count("asdfkasdflasdfl222").

As far as the actual question "How to count digits, letters, spaces for a string in Python", at a glance the rest of the "revised code" looks OK except that the return line is not returning the same variables you've used in the rest of the code. To fix it without changing anything else in the code, change numberand wordto digitand letters, making return number,word,space,otherinto return digit,letters,space,other, or better yet return (digit, letters, space, other)to match current behavior while also using better coding style and being explicit as to what type of value is returned (in this case, a tuple).

至于实际问题“如何在 Python 中计算字符串的数字、字母、空格”,一目了然,“修订后的代码”的其余部分看起来还可以,只是返回行没有返回您使用过的相同变量在其余的代码中。要在不更改代码中的任何其他内容的情况下修复它,将numberand更改worddigitand letters,制作return number,word,space,otherreturn digit,letters,space,other,或者更好return (digit, letters, space, other)地匹配当前行为,同时还使用更好的编码风格并明确返回什么类型的值(在这种情况下,元组)。

回答by Gunjan Thareja

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  

回答by Arpitt Desai

INPUT :

输入 :

1

1

26

26

sadw96aeafae4awdw2 wd100awd

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

OUTPUT :

输出 :

4

4

1

1

19

19

The four digits are 96, 4, 2, 100 The number of spaces = 1 number of letters = 19

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

回答by younesbayh

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

回答by brickbobed

Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function len.

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

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

Alphabetical:

按字母顺序:

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

More info - https://docs.python.org/3/library/re.html

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

回答by Shafat Ahmad

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