python - (python 3)如何检查非字符串是否以元音开头?
问题描述
问题:我正在尝试检查类属性中的元音。
目标是根据 self.type 的第一个字母是否为元音来使用“a”或“an”。
我试过搜索,但所有的回复都是关于常规字符串的。
如何检查 self.type 是否以元音开头?
有一个更好的方法吗?
class robot:
def __init__(self, name, color, type):
self.name = name
self.color =color
self.type = type
def robot_intro(self):
print("My name is", self.name)
print("I am", self.color)
if self.type.lower() startswith ("a","e","i","o","u"):
print("I am an", self.type)
else:
print("I am a", self.type)
r1 = robot("C3PO", "gold", "protocol droid")
r2 = robot("R2D2", "white and blue", "astromech droid")
r3 = robot("BB8", "white and orange", "astromech droid")
r1.robot_intro()
r2.robot_intro()
r3.robot_intro()
解决方案
type
是一个字符串,它是一个类属性并不重要。将其视为常规字符串。甚至属性也是具有基本类型(例如整数、浮点数、字符串、列表)或更复杂类型(如另一个类)的变量。
至于您的问题,以下几行检查第一个字母是否为元音:
if self.type.lower()[0] in ["a","e","i","o","u"]:
print("I am an", self.type)
else:
print("I am a", self.type)
self.type.lower()[0]
返回小写的第一个字母self.type
。然后它搜索它是否在列表中["a","e","i","o","u"]
推荐阅读
- python - LDA模型和joblib并行计算错误
- javascript - 显示对象属性没有排序
- python - Python:查找数组元素的字符之间的距离
- amazon-web-services - 使用与预签名 URL 一致的请求者付款?
- perl - Qwizard 安装失败,“尝试复制释放的标量”
- python - Python 莫名其妙地增加了函数中的列表大小
- spring-boot - 在 Spring Boot 中使用时为控制器使用不同的包
- python - PySpark 无法导入 collect_list,函数没有 collect_list 为什么?
- php - php从午夜获取小时差范围失败
- r-markdown - Stan 代码块在 HTML 输出中不可见