首页 > 解决方案 > 将字符串中的最后一个字母附加到另一个字符串

问题描述

我正在构建一个用 Python 押韵的聊天机器人。是否可以在一个随机单词中识别最后一个元音(以及该元音之后的所有字母),然后将这些字母附加到另一个字符串,而不必一个一个地遍历所有可能的字母(如下例所示)

lastLetters = ''    # String we want to append the letters to

if user_answer.endswith("a")
    lastLetters.append("a")

else if user_answer.endswith("b")
    lastLetters.append("b")

就像如果这个词是对的,我们想要得到“正确”</p>

标签: python

解决方案


您需要找到元音的最后一个索引,因为您可以这样做(有点花哨):

s = input("Enter the word: ") # You can do this to get user input
last_index = len(s) - next((i for i, e in enumerate(reversed(s), 1) if e in "aeiou"), -1)
result = s[last_index:]
print(result)

输出

ight

使用正则表达式的替代方法:

import re

s = "right"
last_index = -1
match = re.search("[aeiou][^aeiou]*$", s)
if match:
    last_index = match.start()

result = s[last_index:]
print(result)

该模式[aeiou][^aeiou]*$表示匹配一个元音,后跟可能不是元音的几个字符([^aeiou]表示不是元音,括号内的符号 ^ 表示正则表达式中的否定)直到字符串的末尾。所以基本上匹配最后一个元音。请注意,这假设字符串仅由辅音和元音组成。


推荐阅读