首页 > 解决方案 > (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()

标签: pythonpython-3.x

解决方案


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"]


推荐阅读