Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of letters in a string without the spaces?

Tags:

python

This is my solution resulting in an error. Returns 0

PS: I'd still love a fix to my code :)

from collections import Counter
import string


def count_letters(word):
    global count
    wordsList = string.split(word)
    count = Counter()
    for words in wordsList:
        for letters in set(words):
            return count[letters]

word = "The grey old fox is an idiot"
print count_letters(word)
like image 471
Ali Gajani Avatar asked Aug 27 '13 00:08

Ali Gajani


People also ask

How do you count letters in a string without spaces?

' ▪︎get length (=number of total characters) of the string by using len(text) ▪︎ get number of spaces by using text. count(' ') ▪︎ subtract number of spaces from total length you can do this with one line of code ! happy coding !

How do you count the number of characters in a string except spaces in Python?

Method #1 : Using isspace() + sum() In this, we check for each character to be equal not to space() using isspace() and not operator, sum() is used to check frequency.

How do you count spaces in a string?

To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the string.


2 Answers

def count_letters(word):
    return len(word) - word.count(' ')

Alternatively, if you have multiple letters to ignore, you could filter the string:

def count_letters(word):
    BAD_LETTERS = " "
    return len([letter for letter in word if letter not in BAD_LETTERS])
like image 162
Matt Bryant Avatar answered Oct 16 '22 04:10

Matt Bryant


Simply solution using the sum function:

sum(c != ' ' for c in word)

It's a memory efficient solution because it uses a generator rather than creating a temporary list and then calculating the sum of it.

It's worth to mention that c != ' ' returns True or False, which is a value of type bool, but bool is a subtype of int, so you can sum up bool values (True corresponds to 1 and False corresponds to 0)

You can check for an inheretance using the mro method:

>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]

Here you see that bool is a subtype of int which is a subtype of object.

like image 36
pkacprzak Avatar answered Oct 16 '22 05:10

pkacprzak