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=str(input("Enter any sentence: "))
s=string.split()
a=0
b=0
for i in s:
a=len(i)
b=a+b
print(b)
It works perfectly without counting spaces of a string
讨论(0)
-
I managed to condense it into two lines of code:
string = input("Enter your string\n")
print(len(string) - string.count(" "))
讨论(0)
-
Counting number of letters in a string using regex.
import re
s = 'The grey old fox is an idiot'
count = len(re.findall('[a-zA-Z]',s))
讨论(0)
-
MattBryant's answer is a good one, but if you want to exclude more types of letters than just spaces, it will get clunky. Here's a variation on your current code using Counter
that will work:
from collections import Counter
import string
def count_letters(word, valid_letters=string.ascii_letters):
count = Counter(word) # this counts all the letters, including invalid ones
return sum(count[letter] for letter in valid_letters) # add up valid letters
Example output:
>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22
讨论(0)
-
def count_letter(string):
count = 0
for i in range(len(string)):
if string[i].isalpha():
count += 1
return count
print(count_letter('The grey old fox is an idiot.'))
讨论(0)
-
OK, if that's what you want, here's what I would do to fix your existing code:
from collections import Counter
def count_letters(words):
counter = Counter()
for word in words.split():
counter.update(word)
return sum(counter.itervalues())
words = "The grey old fox is an idiot"
print count_letters(words) # 22
If you don't want to count certain non-whitespace characters, then you'll need to remove them -- inside the for
loop if not sooner.
讨论(0)
- 热议问题