Skip to content Skip to sidebar Skip to footer

Using Len For Text But Discarding Spaces In The Count

So, I am trying to create a program which counts the number of characters in a string which the user inputs, but I want to discard any spaces that the user enters. def main():

Solution 1:

Count the length and subtract the number of spaces:

>>>full_name = input("Please enter in a full name: ")
Please enter in a full name: john smith
>>>len(full_name) - full_name.count(' ')
9
>>>len(full_name)

Solution 2:

Use sum with a generator expression:

>>>text = 'foo  bar  spam'>>>sum(len(x) for x in text.split())
10

Or str.translate with len:

>>>from string import whitespace>>>len(text.translate(None, whitespace)) #Handles all types of whitespace characters
10

Solution 3:

To count the number of characters excluding spaces, you can simply do:

>>>full_name = "John DOE">>>len(full_name) - full_name.count(' ')
7

Solution 4:

I can propose a few versions.

You can replace each space with an empty string and calculate the length:

len(mystr.replace(" ", ""))

You can calculate the length of the whole string and subtract the number of spaces:

len(mystr) - mystr.count(' ')

Or you can sum the lengths of all substrings after splitting the string with spaces:

sum(map(len, mystr.split(' ')))

Solution 5:

Some code as close as possible to your original:

def main():
    full_name = input("Please enter in a full name: ").split()
    total = 0
    for x in full_name:
        total += len(x)
    print(total)

However, I think len(full_name) - full_name.count(' ') is better.

Post a Comment for "Using Len For Text But Discarding Spaces In The Count"