简体   繁体   中英

How to find a word in a sentence that starts and ends with the same letter?

Is there a way to write "for" loop and "If Else" in python that searches through a sentence and find the number of words that start and end with the same letter? I've tried writing something like:

sentence = "Mom knock the door"

list = sentence.split()
for word in sentence:
    if ...

simply compare the character at the beginning of the string with the character at the end of the string like so:

if word[0] == word[-1]:

If it shouldn't be case sensitive, lower the word first by calling:

word = word.lower()
words_list = sentence.split()
new_words_list = []
for word in words_list:
    if word[0] == word[-1]:
        new_words_list.append(word)

print('Number of words that starts and ends with same letter - {}'.format(len(new_words_list)))

Also you can do it with list comprehension:

new_words_list = [word for word in words_list if word[0] == word[-1]]

If you want not to have it case sensitive use word[0].lower() and word[-1].lower() instead of word[0] and word[-1]

The answers above are all smart, I prefer to deal with it in functional programming way, like this:

sentence = "Mom knock the door"


def is_same_letter_at_begin_end(word):
    return word and word[0].lower() == word[-1].lower()


target_words = list(filter(is_same_letter_at_begin_end, sentence.split()))
print(target_words)
print(len(target_words))
list = sentence.split(" ")
count = 0
for word in list:
    lc_word = word.lower()
    if lc_word[0] == lc_word[-1]:
        count +=1
lst = sentence.split()
num_words = 0
for i in lst:
    low = i.lower()
    if low[0] == low[len(low)-1]:
        num_words += 1
return num_words

list or set comprehension case insensitive:

sentence = "Mom knock the door, mom"
all_words_count = len([ word for word in sentence.split() if word[0].lower() == word[-1].lower() ])
uniq_words_count = len({word.lower() for word in sentence.split() if word[0].lower() == word[-1].lower()})

print(all_words_count) #=> 3
print(uniq_words_count) #=> 2

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