Counting Letters Numbers And Punctuation In A String
How can I write a program that counts letters, numbers and punctuation(separately) in a string?
Solution 1:
For a slightly more condensed / faster version, there is also
count = lambda l1,l2: sum([1 for x in l1 if x in l2])
so for example:
count = lambda l1,l2: sum([1for x in l1 if x in l2])
In [11]: s ='abcd!!!'In [12]: count(s,set(string.punctuation))
Out[12]: 3
using a set should get you a speed boost somewhat.
also depending on the size of the string I think you should get a memory benefit over the filter as well.
Solution 2:
importstring
a = "I'm not gonna post my homework as question on OS again, I'm not gonna..."
count = lambda l1, l2: len(list(filter(lambda c: c in l2, l1)))
a_chars = count(a, string.ascii_letters)
a_punct = count(a, string.punctuation)
Solution 3:
count_chars = ".arPZ"string = "Phillip S. is doing a really good job."
counts = tuple(string.count(c) for c in count_chars)
print counts
(2, 2, 1, 1, 0)
Solution 4:
>>>import string>>>import operator>>>import functools>>>a = "This, is an example string. 42 is the best number!">>>letters = string.ascii_letters>>>digits = string.digits>>>punctuation = string.punctuation>>>letter_count = len(filter(functools.partial(operator.contains, letters), a))>>>letter_count
36
>>>digit_count = len(filter(functools.partial(operator.contains, digits), a))>>>digit_count
2
>>>punctuation_count = len(filter(functools.partial(operator.contains, punctuation), a))>>>punctuation_count
3
http://docs.python.org/library/string.html
http://docs.python.org/library/operator.html#operator.contains
http://docs.python.org/library/functools.html#functools.partial
Solution 5:
To loop over a string you can use a for-loop:
for c in"this is a test string with punctuation ,.;!":
print c
outputs:
t
h
i
s
...
Now, all you have to do is count the occurrences...
Post a Comment for "Counting Letters Numbers And Punctuation In A String"