python - 将字符串中的最后一个字母附加到另一个字符串
问题描述
我正在构建一个用 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>
解决方案
您需要找到元音的最后一个索引,因为您可以这样做(有点花哨):
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]
表示不是元音,括号内的符号 ^ 表示正则表达式中的否定)直到字符串的末尾。所以基本上匹配最后一个元音。请注意,这假设字符串仅由辅音和元音组成。
推荐阅读
- html - margin-left 的属性值无效:auto
- node.js - 如何将获取数据设置到 React-Native 表中
- python - 如何在 AWS 中为 AWS lambda 函数模拟 s3.Object
- webpack - Happy pack semver 问题 webpack build
- wordpress - WordPress - 如何仅从 git 存储库跟踪主题文件夹
- mvvmcross - 当有多个测试类时,“您应该只初始化 MvxBindingSingletonCache 一次”错误
- powershell - 如何将对象数组拆分为数组中的单独变量
- dart - 如何将函数字节转换为飞镖
- r - 避免R中for循环的巧妙方法
- swift - AVAssetExportSession 将视频导出到照片库