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)
2
  • 1
    check this. stackoverflow.com/questions/31845482/…. you can't use for s in joke Commented Feb 9, 2018 at 2: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 Commented Feb 9, 2018 at 2:52

6 Answers 6

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]
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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)

Comments

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']

Comments

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)]

Comments

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)

Comments

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)

1 Comment

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.