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

I am trying to make a function to detect how many digits, letter, spaces, and others for a string.

Here's what I have so far:

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

But it's not working:

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

What's wrong with my code and how can I improve it to a more simple and precise solution?

This question is related to python string counting

The answer is


Here's another option:

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

Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function 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


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


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

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(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.

To fix your call to your function, just add quotes around asdfkasdflasdfl222 changing count(asdfkasdflasdfl222) to 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 number and word to digit and letters, making return number,word,space,other into 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).


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

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

There are 2 errors is this code:

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

x = []

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

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

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  

INPUT :

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

OUTPUT :

4

1

19

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


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to counting

How to count digits, letters, spaces for a string in Python? How do I count unique visitors to my site? Counting the number of True Booleans in a Python List Find the item with maximum occurrences in a list How to count the frequency of the elements in an unordered list? Item frequency count in Python