简体   繁体   中英

Using a For Loop to Change Words in Strings to List Items

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)

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]

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM