2

How can I write a program that counts letters, numbers and punctuation(separately) in a string?

Tamera
  • 61
  • 1
  • 1
  • 2

5 Answers5

8

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([1 for 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.

Eiyrioü von Kauyf
  • 4,481
  • 7
  • 32
  • 41
4
import string
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)
BrainStorm
  • 2,036
  • 1
  • 16
  • 23
2
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)

Niklas R
  • 16,299
  • 28
  • 108
  • 203
1
>>> 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

http://docs.python.org/library/functions.html#len

http://docs.python.org/library/functions.html#filter

utdemir
  • 26,532
  • 10
  • 62
  • 81
0

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...

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130