Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to know how many strings are there in the given list

list = [56, Tree, 776, 89, Five, One, 43, Apple]


By looking at the list we can say there are 4 strings in the list

What I have tried:

print(list.count(type(str)))

But no success
Posted
Updated 27-Sep-22 4:56am
v2
Comments
Afzaal Ahmad Zeeshan 8-Oct-21 19:26pm    
None of them are strings; they are variables? If not, then they are invalid characters in Python.

This isn't perfect at all, but ...
Python
a = [56, "Tree", 776, 89, "Five", "One", 43, "Apple"]
print([x for x in a if not str(x).isdigit()])
 
Share this answer
 
Elaborating (plagiarizing) Griff's answer...
Python
a = [56, "Tree", 776, 89, "Five", "One", True, (True, "Goo"),  "Apple"]
b = [x for x in a if isinstance(x, str)]
print(len(b))
 
Share this answer
 
v2
c=0
for i in list:
if type(i)==str:
c=c+1
print("The Numbers of strings is",c)
 
Share this answer
 
list1 = [56, 'Tree', 776, 89, 'Five', 'One', 43, 'Apple']
str_num = sum(type(x) == str for x in list1) #str_num is the number of strings in list1
print(str_num)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900