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.
You can also do
sum(1 for c in s if c!=' ')
Which avoids any unnecessary temporary string or list.
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
Why can't you just do:
>>> mystr = input("Please enter in a full name: ")
Please enter in a full name: iCodez wrote this
>>> len(mystr.replace(" ", ""))
15
>>> len(mystr)
17
>>>
This gets the length of the string minus the spaces.
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(' ')))
To count the number of characters excluding spaces, you can simply do:
>>> full_name = "John DOE"
>>> len(full_name) - full_name.count(' ')
7
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)