Python 程式接受以母音開頭的字串
當需要接受一個以母音字母開頭的字串時,可以使用“startswith”函式來檢查字串是否以特定字元(母音)開頭。
示例
以下是演示
my_list = ["Hi", "there", "how", "are", "u", "doing"] print("The list is : ") print(my_list) my_result = [] vowel = "aeiou" for sub in my_list: flag = False for letter in vowel: if sub.startswith(letter): flag = True break if flag: my_result.append(sub) print("The resultant string is : ") print(my_result)
輸出
The list is : ["Hi", "there", "how", "are", "u", "doing"] The resultant string is : ['are', 'u']
解釋
定義了一個列表並顯示在控制檯上。
定義一個空列表。
母音在字串中進行定義。
迭代遍歷列表並分配“flag”變數為 False。
將字串中的字母與母音字串進行比較。
使用“startswith”方法檢查列表中的字串是否以母音開頭。
如果是,則顯示在控制檯上。
廣告