How to Count Chars in a String with Python


In this example we will show how to count the number of items in a string using Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import string
s = input('Please input a string:n')
letters = 0
space = 0
digit = 0
others = 0
i=0
while i < len(s):
    c = s[i]
    i += 1
    if c.isalpha():
        letters += 1
    elif c.isspace():
        space += 1
    elif c.isdigit():
        digit += 1
    else:
        others += 1
print('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))

Output:

Please input a string:
 heho345uaenor  fhohto$anf oh*fo @dsof
char = 27,space = 4,digit = 3,others = 3
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments