Reputation:
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 ...
Upvotes: 1
Views: 2717
Reputation: 2255
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))
Upvotes: 1
Reputation: 11183
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
Upvotes: 0
Reputation: 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
Upvotes: 0
Reputation: 2086
list = sentence.split(" ")
count = 0
for word in list:
lc_word = word.lower()
if lc_word[0] == lc_word[-1]:
count +=1
Upvotes: 0
Reputation: 5669
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]
Upvotes: 1
Reputation: 627
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()
Upvotes: 2