Python count characters in word

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a String. The task is to return the number of characters in the string.

    Examples:

    Input : test_str = ‘geeksforgeeks !!$*** best 4 all Geeks 10-0’ 
    Output : 25
    Explanation : Only alphabets, when counted are 25

    Input : test_str = ‘geeksforgeeks !!$*** best for all Geeks 10—0’ 
    Output : 27
    Explanation : Only alphabets, when counted are 27

    Method #1 : Using isalpha() + len()

    In this approach, we check for each character to be alphabet using isalpha() and len() is used to get the length of the list of alphabets to get count.

    Python3

    test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'

    print("The original string is : " + str(test_str))

    res = len([ele for ele in test_str if ele.isalpha()])

    print("Count of Alphabets : " + str(res))

    Output

    The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0
    Count of Alphabets : 27

    Time Complexity: O(n)
    Auxiliary Space: O(n)

    Method #2: Using ascii_uppercase() + ascii_lowercase() + len()

    In this, we perform the task of getting alphabets as a combination of upper and lowercase, using inbuilt functions, len() returns frequency.

    Python3

    import string

    test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'

    print("The original string is : " + str(test_str))

    res = len([ele for ele in test_str if ele in string.ascii_uppercase or ele in string.ascii_lowercase])

    print("Count of Alphabets : " + str(res))

    Output

    The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0
    Count of Alphabets : 27

    Time Complexity: O(n)
    Auxiliary Space: O(n)

    Method 3: Using the sum() function 

    Use the sum() function along with a generator expression that checks if each character in the string is an alphabet using isalpha().

    Python3

    test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'

    print("The original string is : " + str(test_str))

    res = sum(1 for c in test_str if c.isalpha())

    print("Count of Alphabets : " + str(res))

    Output

    The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0
    Count of Alphabets : 27

    Time Complexity: O(n)
    Auxiliary Space: O(1)

    Like Article

    Save Article

    In Python, we can easily count the letters in a word using the Python len() function and list comprehension to filter out characters which aren’t letters.

    def countLetters(word):
        return len([x for x in word if x.isalpha()])
    
    print(countLetters("Word."))
    print(countLetters("Word.with.non-letters1"))
    
    #Output:
    4
    18

    This is equivalent to looping over all letters in a word and checking if each character is a letter.

    def countLetters(word):
        count = 0
        for x in word:
            if x.isalpha():
                count = count + 1
        return count
    
    print(countLetters("Word."))
    print(countLetters("Word.with.non-letters1"))
    
    #Output:
    4
    18

    If you’d like to get the count of each letter in Python, you can use the Python collections module.

    import collections
    
    print(collections.Counter("Word"))
    
    #Output:
    Counter({'W': 1, 'o': 1, 'r': 1, 'd': 1})

    If you’d like to get the letters of all words in a string, we can use the Python split() function in combination with the len() function.

    string_of_words = "This is a string of words."
    
    letter_counts = []
    for x in string_of_words.split(" "):
        letter_counts.append(len([x for x in word if x.isalpha()]))
    
    print(letter_counts)
    
    #Output:
    [4, 2, 1, 6, 2, 5]

    When working with strings, it is very useful to be able to easily extract information about our variables.

    One such piece of information which is valuable is the number of letters a string has.

    We can use the Python len() function to get the number of letters in a string easily.

    print(len("Word"))
    
    #Output:
    4

    If you have a string with punctuation or numbers in it, we can use list comprehension to filter out the characters which aren’t letters and then get the length of this new string.

    def countLetters(word):
        return len([x for x in word if x.isalpha()])
    
    print(countLetters("Word."))
    print(countLetters("Word.with.non-letters1"))
    
    #Output:
    4
    18

    If you don’t want to use list comprehension, loop over each element in the string and see if it is a letter or not with the Python isalpha() function.

    def countLetters(word):
        count = 0
        for x in word:
            if x.isalpha():
                count = count + 1
        return count
    
    print(countLetters("Word."))
    print(countLetters("Word.with.non-letters1"))
    
    #Output:
    4
    18

    Finding Count of All Letters in a Word Using Python

    In Python, we can also find the unique count of all letters in a word, and the number of times each letter appears in a word.

    The Python collections module is very useful and provides a number of functions which allow us to create new data structures from lists.

    One such data structure is the Counter data structure.

    The Counter data structure counts up all of the occurrences of a value in a list.

    To get the count of all letters in a word, we can use the Python collections Counter data structure in the following Python code.

    import collections
    
    print(collections.Counter("Word"))
    
    #Output:
    Counter({'W': 1, 'o': 1, 'r': 1, 'd': 1})

    If you then want to get the count of any particular letter, you can access the count just like you would access a value in a dictionary.

    import collections
    
    c = collections.Counter("Word")
    
    print(c["W"])
    
    #Output:
    1

    Counting Letters of All Words in a String Using Python

    When processing strings in a program, it can be useful to know how many words there are in the string, and how many letters are in each word. Using Python, we can easily get the number of letters in each word in a string with the Python len() function.

    Let’s say you have a string which is a sentence (in other words, each word in the sentence is delimited by a space).

    We can use the Python split() function to change the string into a list, and then loop over the list to get the length of each word in a string.

    Below is a Python function which will count the letters in all words in a string using Python.

    string_of_words = "This is a string of words."
    
    letter_counts = []
    for x in string_of_words.split(" "):
        letter_counts.append(len([x for x in word if x.isalpha()]))
    
    print(letter_counts)
    
    #Output:
    [4, 2, 1, 6, 2, 5]

    Hopefully this article has been useful for you to learn how to count letters in words in Python.

    In this tutorial, we will learn about the Python String count() method with the help of examples.

    The count() method returns the number of occurrences of a substring in the given string.

    Example

    message = 'python is popular programming language'
    
    

    # number of occurrence of 'p' print('Number of occurrence of p:', message.count('p'))

    # Output: Number of occurrence of p: 4

    Syntax of String count

    The syntax of count() method is:

    string.count(substring, start=..., end=...)

    count() Parameters

    count() method only requires a single parameter for execution. However, it also has two optional parameters:

    • substring — string whose count is to be found.
    • start (Optional) — starting index within the string where search starts.
    • end (Optional) — ending index within the string where search ends.

    Note: Index in Python starts from 0, not 1.


    count() Return Value

    count() method returns the number of occurrences of the substring in the given string.


    Example 1: Count number of occurrences of a given substring

    # define string
    string = "Python is awesome, isn't it?"
    substring = "is"
    
    

    count = string.count(substring)

    # print count print("The count is:", count)

    Output

    The count is: 2

    Example 2: Count number of occurrences of a given substring using start and end

    # define string
    string = "Python is awesome, isn't it?"
    substring = "i"
    
    # count after first 'i' and before the last 'i'
    

    count = string.count(substring, 8, 25)

    # print count print("The count is:", count)

    Output

    The count is: 1

    Here, the counting starts after the first i has been encountered, i.e. 7th index position.

    And, it ends before the last i, i.e. 25th index position.

    Last update on August 19 2022 21:51:43 (UTC/GMT +8 hours)

    Python String: Exercise-2 with Solution

    Write a Python program to count the number of characters (character frequency) in a string.

    Python String Exercises: Count the number of characters (character frequency) in a string

    Sample Solution:-

    Python Code:

    def char_frequency(str1):
        dict = {}
        for n in str1:
            keys = dict.keys()
            if n in keys:
                dict[n] += 1
            else:
                dict[n] = 1
        return dict
    print(char_frequency('google.com'))
    
    

    Sample Output:

    {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
    

    Flowchart:

    Flowchart: Program to count the number of characters in a string

    Visualize Python code execution:

    The following tool visualize what the computer is doing step-by-step as it executes the said program:

    Python Code Editor:

    Have another way to solve this solution? Contribute your code (and comments) through Disqus.

    Previous: Write a Python program to calculate the length of a string.
    Next: Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.

    What is the difficulty level of this exercise?

    Test your Programming skills with w3resource’s quiz.

    

    Python: Tips of the Day

    Casts the provided value as a list if it’s not one:

    Example:

    def tips_cast(val):
      return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
    
    print(tips_cast('bar'))
    print(tips_cast([1]))
    print(tips_cast(('foo', 'bar')))
    

    Output:

    ['bar']
    [1]
    ['foo', 'bar']
    


    • Weekly Trends
    • Java Basic Programming Exercises
    • SQL Subqueries
    • Adventureworks Database Exercises
    • C# Sharp Basic Exercises
    • SQL COUNT() with distinct
    • JavaScript String Exercises
    • JavaScript HTML Form Validation
    • Java Collection Exercises
    • SQL COUNT() function
    • SQL Inner Join
    • JavaScript functions Exercises
    • Python Tutorial
    • Python Array Exercises
    • SQL Cross Join
    • C# Sharp Array Exercises


    Понравилась статья? Поделить с друзьями:
  • Python capitalize every word
  • Python microsoft word linux
  • Python capitalize each word in string
  • Python make excel file
  • Python load from excel