Count letters in word python

The other answers show what’s wrong with your code. But there’s also a built-in way to do this, if you weren’t just doing this for an exercise:

>>> 'banana'.count('a')
3

Danben gave this corrected version:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

Here are some other ways to do it, hopefully they will teach you more about Python!

Similar, but shorter for loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:

def count_letters(word, char):
  count = 0
  for c in word:
    count += (char == c)
  return count

Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn’t match char and 1 if it does, and then sums them:

def count_letters(word, char):
  return sum(char == c for c in word)

The next one filters out all the characters that don’t match char, and counts how many are left:

def count_letters(word, char):
  return len([c for c in word if c == char])

Given a string, containing digits and letters, the task is to write a Python program to calculate the number of digits and letters in a string. 

Example:

Input: string = "geeks2for3geeks"
Output: total digits = 2 and total letters = 13

Input: string = "python1234"
Output: total digits = 4 and total letters = 6

Input: string = "co2mpu1te10rs"
Output: total digits = 4 and total letters = 9
 
Explanation: Here we are calculating the number of digits and alphabets in the given string.

Method 1: Using the built-in method isalpha()

Python3

alpha,string=0,"Geeks1234"

for i in string:

    if (i.isalpha()):

        alpha+=1

print("Number of Digit is", len(string)-alpha)

print("Number of Alphabets is", alpha)

Output:

Number of Digit is 4
Number of Alphabets is 5

Explanation:

Here we have used the built-in method isalpha() which generally helps us to identify whether that particular character is a alphabet or not and if it’s not then we simply ignore it. Assuming the condition that the string only constitutes of alphabets and digits then we can conclude that whether that character will be a digit or a alphabet. We already have the count of all the alphabets then we can subtract the count with the length of the string and hence we can get the number of digits.

Time complexity :  O(n)

Space complexity : O(1)

Method 2: Using all digit and all letter lists

Python3

all_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',

               'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

string = "geeks2for3geeks"

total_digits = 0

total_letters = 0

for s in string:

    if s in all_digits:

        total_digits += 1

    elif s in all_letters:

        total_letters += 1

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output:

Total letters found :- 13
Total digits found :- 2

Explanation:

The idea here is to solve this problem by iterating through all characters and checking whether the character is in all_digits that store all the digits or all_letters that store all the alphabets in list. 

Time complexity : O(n)

Space complexity : O(1)

Method 3: By just checking one of the above conditions

Python3

all_digits = ['0', '1', '2', '3', '4',

              '5', '6', '7', '8', '9']

all_letters = ['a', 'b', 'c', 'd', 'e', 'f',

               'g', 'h', 'i', 'j', 'k', 'l',

               'm', 'n', 'o', 'p', 'q', 'r',

               's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

string = "geeks2for3geeks"

total_digits = 0

total_letters = 0

for s in string:

    if s in all_digits:

        total_digits += 1

    else:

        total_letters += 1

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output:

Total letters found :- 13
Total digits found :- 2

Explanation:

Instead of checking characters in all_letters, we can check:  

  • if the character is found in all digits, then increment the total_digits value by one
  • If not it means characters is a letter, increment total_letters value by one

Time complexity :  O(n)

Space complexity : O(1)

Method 3: By using the built in method isnumeric()

Python3

string = "python1234"

total_digits = 0

total_letters = 0

for s in string:

    if s.isnumeric():

        total_digits += 1

    else:

        total_letters += 1

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output:

Total letters found :- 6
Total digits found :- 4

Explanation:

The idea here is to solve this problem by iterating through all characters and checking whether the character is a letter or digits using isnumeric() function. If isnumeric() is True, it means a character is a digit, else character is a letter.

Time Complexity : O(n)

Space Complexity : O(1)

Method 4: Using re.findall() and len() function

Python3

import re

string = "geeks2for3geeks"

total_digits = len(re.findall('[0-9]',string))

total_letters = len(re.findall('[A-z]', string))

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output:

Total letters found :- 13
Total digits found :- 2

Explanation:

Here we use these function which make our solution more easy. First we find all the digits in string with the help of re.findall() which give list of matched pattern with the help of len we calculate the length of list and similarly we find the total letters in string with the help of re.findall() method and calculate the length of list using len. 

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)

Method 5: Using ord() function

Python3

string = "geeks2for3geeks"

total_digits = 0

total_letters = 0

for s in string:

    if ord(s) in range(48,58):

        total_digits += 1

    elif ord(s) in range(65,91) or ord(s) in range(97,123):

        total_letters += 1

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output:

Total letters found :- 13
Total digits found :- 2

Explanation:

Here we are using the ord() function which returns the ascii code of the character and hence we compare it in their respective zones or range and get the count of digits and alphabets separately.

Time Complexity : O(n)

Space Complexity : O(1)

Method 6:  using operator.countOf() method

Python3

import operator as op

all_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',

               'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

string = "geeks2for3geeks"

total_digits = 0

total_letters = 0

for s in string:

    if op.countOf(all_digits, s) > 0:

        total_digits += 1

    elif op.countOf(all_letters, s) > 0:

        total_letters += 1

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output

Total letters found :- 13
Total digits found :- 2

Time Complexity: O(N)

Auxiliary Space : O(1)

Method 7:  using isalpha() and isdigit():

Python3

string = "geeks2for3geeks"

total_letters = sum([1 for char in string if char.isalpha()])

total_digits = sum([1 for char in string if char.isdigit()])

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output

Total letters found :- 13
Total digits found :- 2

Time Complexity: O(N)

Auxiliary Space : O(1)

Method 8:  Using try/except

Explanation:

In this approach, we use the try and except statements to determine if the character can be converted to an integer or not. If it can, it means the character is a digit, so we increment the total_digits count. If it can’t be converted, it means the character is a letter, so we increment the total_letters count.

Python3

string = "geeks2for3geeks"

total_digits = 0

total_letters = 0

for s in string:

    try:

        int(s)

        total_digits += 1

    except:

        total_letters += 1

print("Total letters found :-", total_letters)

print("Total digits found :-", total_digits)

Output

Total letters found :- 13
Total digits found :- 2

Time complexity: O(n)

Auxiliary Space: O(1)

Counter is definitely the way to go (and I’ve upvoted Jaime’s answer).

If you want to do it yourself and iterate only once, this should work :

d={}
for l in s:
        d[l] = d.get(l,0) + 1

There might be a short/more pythonic way to do so but it works…

Edit :
I must confess that Jaime’s comment to this answer surprised me but I’ve just tested this code :

from profilehooks import profile

s="qwertyuiopasdfghjklzxcvbnm"

@profile
def function1(s):
        d={}
        for l in s:
                d[l] = d.get(l,0)+1
        return d

@profile
def function2(s):
        return dict((char_, s.count(char_)) for char_ in set(s))

for i in xrange(0,200):
        function1(s*i)
        function2(s*i)

And the results can hardly be contested :

*** PROFILER RESULTS ***
function2 (./fsdhfsdhjk.py:13)
function called 200 times

         10948 function calls in 0.161 seconds

   Ordered by: cumulative time, internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      200    0.083    0.000    0.161    0.001 fsdhfsdhjk.py:13(function2)
     5374    0.033    0.000    0.077    0.000 fsdhfsdhjk.py:15(<genexpr>)
     5174    0.044    0.000    0.044    0.000 {method 'count' of 'str' objects}
      200    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        0    0.000             0.000          profile:0(profiler)



*** PROFILER RESULTS ***
function1 (./fsdhfsdhjk.py:6)
function called 200 times

         517800 function calls in 2.891 seconds

   Ordered by: cumulative time, internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      200    1.711    0.009    2.891    0.014 fsdhfsdhjk.py:6(function1)
   517400    1.179    0.000    1.179    0.000 {method 'get' of 'dict' objects}
      200    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        0    0.000             0.000          profile:0(profiler)

TL;DR
Jaime’s solution (function2) is 18 times faster than mine (function1).

Let us suppose that we have a string and we have to calculate the total number
of digits and letters present in the string.

For Example

Input 

s = “tutorialsP0int”

Output 

Letters: 13
Digits: 1

Explanation

Total number of letters and digits present in the given string are 13 and 1.

Approach to Solve this Problem

To calculate the total number of letters and digits in the given string, we have to
first iterate over the whole string. If we get an alphabet, then we increment the
letter count; otherwise, if we extract a digit, then increment the digit count.

  • Take an input string.

  • While iterating over the whole string, if we find a digit, then increment the
    count of digits; otherwise, if we find a letter, then increment the count of
    letters.

  • Return the count of letters and digits as the output.

Example

str = "tutorialsP0int"
digit=letter=0
for ch in str:
   if ch.isdigit():
      digit=digit+1
   elif ch.isalpha():
      letter=letter+1
   else:
      pass
print("Letters:", letter)
print("Digits:", digit)

Output

Running the above code will generate the output as follows −

Letters: 13
Digits: 1

Понравилась статья? Поделить с друзьями:
  • Count letter in word python
  • Count in excel with filter
  • Count in excel with duplicates
  • Count in excel for text
  • Count in excel by name