rmahesh
rmahesh

Reputation: 749

Count the number of digits and letters inside a list?

Say that list(x) = ["12/12/12", "Jul-23-2017"]

I want to count the number of letters (which in this case is 0) and the number of digits (which in this case is 6).

I tried calling x[i].isalpha() and x[i].isnumeric() while iterating through a for loop and an error was thrown stating

"TypeError: list indices must be integers or slices, not str"

Any help would be greatly appreciated!

Upvotes: 0

Views: 4337

Answers (4)

cdlane
cdlane

Reputation: 41872

How about:

def analyze(s):
    return [sum(n) for n in zip(*((c.isdigit(), c.isalpha()) for c in s))]

strings = ["12/12", "12/12/12", "Jul-23-2017"]

for string in strings:
    print(analyze(string), string)

OUTPUT

[4, 0] 12/12
[6, 0] 12/12/12
[6, 3] Jul-23-2017

I set the first sum to equal a variable called "digits" and the second sum to a variable called "letters"

digits, letters = analyze("Jul-23-2017")

Upvotes: 2

user2399453
user2399453

Reputation: 3081

You can do something like this:

def count(L):
  dgt=0
  letters=0
  for s in L:
    for c in s:
      if str(c).isdigit():
        dgt+=1
      elif str(c).isalpha():
        letters+=1
  return (dgt, letters)


>>> count(["12/12/12", "Jul-23-2017"])
#returns (12,3) - There are 12 digits and 3 chars ('J', 'u', 'l')

If you want to print a tuple for each word in the list you can do:

def count(L):
  for word in L:
    yield (sum(s.isdigit() for s in word), sum(s.isalpha() for s in word))

for t in count(L):
 print t
#outputs:
(6, 0)
(6, 3)

Upvotes: 0

EsotericVoid
EsotericVoid

Reputation: 2576

Is this what you want?

x = ["12/12/12", "Jul-23-2017"]
sum(1 for word in x for c in word if c.isdigit())  # 12
sum(1 for word in x for c in word if c.isalpha())  # 3

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36023

Your error indicates that you either did for i in x (which makes no sense) or for i in s (where s is an element of x, a string). What you meant to do was for i in range(len(s)). Even better would be c.isalpha() for c in s.

Upvotes: 5

Related Questions