list = ['abcd','xyz',12,13]
I want to count several strings in the above list. How can we do that?
I used the count method but it didn't work.
How to do that?
list = ['abcd','xyz',12,13]
I want to count several strings in the above list. How can we do that?
I used the count method but it didn't work.
How to do that?
We can use a list comprehension:
list = ['abcd','xyz',12,13]
num = len([x for x in list if isinstance(x, str)])
print(num) # 2
If you want to count only strings in a list
list_one = ['abcd','xyz',12,13]
c = 0
for i in list_one:
if isinstance(i, str):
c += 1
print(c)
If it's actually a list of string numbers like the title suggests, here are a couple of ways to do it
l = ['abcd', 'xyz' , '12' , '13']
# Using try
count = 0
for s in l:
try:
int(s)
count += 1
except ValueError:
pass
print("numbers in list:", count)
count = 0
for s in l:
if s.isdigit():
count += 1
print("numbers in list:", count)
We can also use type() to check string with list comprehension:
list = ['abcd','xyz',12,13]
print(len([x for x in list if type(x) is str]))