1

I am trying to use a for loop to find every word in a string that contains exactly one letter e.

My guess is that I need to use a for loop to first separate each word in the string into its own list (for example, this is a string into ['this'], ['is'], ['a'], ['string'])

Then, I can use another For Loop to check each word/list.

My string is stored in the variable joke.

I'm having trouble structuring my For Loop to make each word into its own list. Any suggestions?

j2 = []

for s in joke:
if s[0] in j2:
    j2[s[0]] = joke.split()
else:
    j2[s[0]] = s[0]
print(j2)
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    check this. https://stackoverflow.com/questions/31845482/iterating-through-a-string-word-by-word. you can't use `for s in joke` – Neville Nazerane Feb 09 '18 at 02:50
  • in future, for variable names use the symbol ` instead of " for clarity. The first implies a part of code (like variable), the second makes it look like a string – Neville Nazerane Feb 09 '18 at 02:52

6 Answers6

8

This is a classic case for list comprehensions. To generate a list of words containing exactly one letter 'e', you would use the following source.

words = [w for w in joke.split() if w.count('e') == 1]
Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37
  • Do note that instead of creating a list for every single word as you stated, it is more efficient to create a single list that contains all the words instead like in `Hans'` answer. – Siddharth Srinivasan Feb 09 '18 at 03:01
2

For finding words with exactly one letter 'e', use regex

import re
mywords = re.match("(\s)*[e](\s)*", 'this is your e string e')
print(mywords)
Tilak Putta
  • 758
  • 4
  • 18
1

I would use Counter:

from collections import Counter
joke = "A string with some words they contain letters"
j2 = []
for w in joke.split():
    d = Counter(w)
    if 'e' in d.keys():
        if d['e'] == 1:
            j2.append(w)

print(j2)

This results in:

['some', 'they']
briancaffey
  • 2,339
  • 6
  • 34
  • 62
1

A different way to do it using numpy which is all against for:

s = 'Where is my chocolate pizza'
s_np = np.array(s.split())
result = s_np[np.core.defchararray.count(s_np, 'e').astype(bool)]
Gerges
  • 6,269
  • 2
  • 22
  • 44
0

This is one way:

mystr = 'this is a test string'    
[i for i in mystr.split() if sum(k=='e' for k in i) == 1]   
# test

If you need an explicit loop:

result = []
for i in mystr:
    if sum(k=='e' for k in i) == 1:
        result.append(i)
jpp
  • 159,742
  • 34
  • 281
  • 339
0
sentence = "The cow jumped over the moon."
new_str = sentence.split()
count = 0
for i in new_str:
    if 'e' in i:
        count+=1
        print(i)
print(count)
Kasem777
  • 737
  • 7
  • 10
  • 1
    I am not sure if that what you are looking for but that gives you how many 'e' and print the word with letter 'e' – Kasem777 Apr 07 '20 at 16:23