为了账号安全,请及时绑定邮箱和手机立即绑定

如何在句子中找到以相同字母开头和结尾的单词?

如何在句子中找到以相同字母开头和结尾的单词?

HUWWW 2021-09-28 16:21:08
有没有办法在python中编写“for”循环和“If Else”来搜索句子并找到以相同字母开头和结尾的单词数?我试过写这样的东西:sentence = "Mom knock the door"list = sentence.split()for word in sentence:    if ...
查看完整描述

3 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

只需将字符串开头的字符与字符串结尾的字符进行比较,如下所示:

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

如果它不应该区分大小写,请先通过调用降低单词:

word = word.lower()


查看完整回答
反对 回复 2021-09-28
?
有只小跳蛙

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]


查看完整回答
反对 回复 2021-09-28
?
慕工程0101907

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


查看完整回答
反对 回复 2021-09-28
  • 3 回答
  • 0 关注
  • 221 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信