Home > Software engineering >  How to count special characters, Alphabets and numbers from a string in python?
How to count special characters, Alphabets and numbers from a string in python?

Time:02-11

string = '98 people are present @ seminar'

def count(string):
    d={}
    for t in string:
        d[t] = string.count(t)
    for k in sorted(d):
        print(k ':'    str(d[k]))
count(string)

here I want to add counters for special characters and numbers. also want to get user input for string. how do I do that?

CodePudding user response:

Python has various string methods to help distinguish alpha and numeric strings. You can test for these and count based on that test.

def count(string):
    d={'letters': 0, 'numbers': 0, 'other': 0}
    for t in string:
        if t.isalpha():
            d['letters']  = 1
        elif t.isdigit():
            d['numbers']  = 1
        else:
            d['other']  = 1 # this will include spaces
    return d

string = input('enter some text: ')
# 98 people are present @ seminar

counts = count(string)
print(counts)
# {'letters': 23, 'numbers': 2, 'other': 6}

CodePudding user response:

To ask for userinput for the string use

variableName = input(PROMPT)

To have a count make a list of nums, list of letters and the rest will be special chars Then loop through the list and use an if statement to check if the letter is in the string with .contains()

The code would look something like this:

letters = "abcdefghijklmnopqrstuvwxyz"
numbers = "0123456789"
def countString(inputString,characterType):#inputString is the string you want to check characterType is what you want to check for
    count = 0
    inputString = inputString.lower()
    if characterType == "numbers":
        for i in inputString:
            if not(numbers.count(i) == 0):
                count  = 1
    elif characterType == "letters":
        for i in inputString:
            if not(letters.count(i) == 0):
                count  = 1     
    elif characterType == "specialChars":
        for i in inputString:
            if numbers.count(i) == 0 and letters.count(i) == 0 and not(i == " ") :
                count  = 1
    return count
  • Related