3 回答
TA贡献1785条经验 获得超8个赞
只需将字符串开头的字符与字符串结尾的字符进行比较,如下所示:
if word[0] == word[-1]:
如果它不应该区分大小写,请先通过调用降低单词:
word = word.lower()
TA贡献1824条经验 获得超8个赞
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)))
你也可以用列表理解来做到这一点:
new_words_list = [word for word in words_list if word[0] == word[-1]]
如果您不想让它区分大小写,请使用word[0].lower()andword[-1].lower()而不是word[0]andword[-1]
TA贡献1887条经验 获得超5个赞
上面的答案都很聪明,我更喜欢用函数式编程的方式来处理,像这样:
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))
添加回答
举报