-2

I'm a Python beginner and need some help here. I've a string with a bunch of words, put them into a list and want to count every word that has 4 characters or more. I found every way to count all elements, but not with a condition. I'm thankful for any help or tutorial I didn't find.

Kendel
  • 35
  • 9
  • 4
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive. – Martijn Pieters Jun 10 '14 at 10:38

3 Answers3

2

Filter your list with a generator expression; using sum() here to count the number of matches is more efficient than to create a filtered list first:

longer_words_count = sum(1 for word in sentence.split() if len(word) >= 4)

I've assumed that you did not yet split the string with words; str.split() does that nicely.

You could do:

longer_words_count = sum(len(word) >= 4 for word in sentence.split())

because Python's boolean type is a subclass of int; True == 1 and False == 0. I dislike using this trick however, as the relation is historical and not explicit.

Demo:

>>> sentence = 'The quick brown fox jumps over the lazy dog'
>>> sum(1 for word in sentence.split() if len(word) >= 4)
5
>>> sum(len(word) >= 4 for word in sentence.split())
5
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

a simple way of doing this is using split to get a list and afterwards count how many of the items have a length of over or equal to 4.

a="abc abc abcde"
listCount=a.split(" ")
counter=0
for item in listCound:
    if len(item)>=4:
        counter+=1
print (counter)
rozi
  • 156
  • 3
0

An alternative would be to make a sublist and have its length, might be less efficient but can give some more useful info, it depends on what you want:

sub_list = [elem for elem in list if len(elem)>4]
len(sub_list)
Dargor
  • 223
  • 3
  • 8