[問題] 比對字串中的母音有幾種

看板Python作者 (tnzikom)時間7年前發表 (2017/11/03 08:39), 7年前編輯推噓3(308)
留言11則, 7人參與, 7年前最新討論串1/1
目前寫了判斷母音的code如下 word = input() count = 0 a = e = i = o = u = 0 for num in word.lower(): if num in 'a': a = 1 elif num in 'e': e = 1 elif num in 'i': i = 1 elif num in 'o': o = 1 elif num in 'u': u = 1 count = a + e + i + o + u print(count) 自己覺得這code看起來很笨......想問是不是有更好的寫法, 另外也想問for num in word.lower()這行for的運作是怎麼樣呢? 知道word.lower()是變小寫的意思, 但num in word.lower()的意思看了很久還是不太能理解> < -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.25.99 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1509698343.A.F90.html ※ 編輯: tnzikom (140.112.25.99), 11/03/2017 17:09:11

11/03 17:38, 7年前 , 1F
for num in word.lower(): if num in 'aeiou': count += 1
11/03 17:38, 1F

11/03 17:39, 7年前 , 2F
(請自行排版) 另外你本來的寫法是錯的,aeiou的值沒有累加
11/03 17:39, 2F
抱歉我打錯了!!!是要問有幾種母音

11/03 17:47, 7年前 , 3F
import re
11/03 17:47, 3F

11/03 17:48, 7年前 , 4F
count=len(re.findall("[AEIOU]", word,re.I))
11/03 17:48, 4F
※ 編輯: tnzikom (140.112.25.99), 11/03/2017 18:29:08

11/03 18:35, 7年前 , 5F
str.count(....)
11/03 18:35, 5F

11/03 21:22, 7年前 , 6F
[ch in word.lower() for ch in 'aeiou'].count(True)
11/03 21:22, 6F

11/03 21:24, 7年前 , 7F
num in word.lower() #小寫的word是否有num變數代表的字母
11/03 21:24, 7F

11/03 22:44, 7年前 , 8F
len( set("aeiou") & set(word) )
11/03 22:44, 8F

11/03 23:27, 7年前 , 9F
word='ptT is Back' for num in word作用如同
11/03 23:27, 9F

11/03 23:28, 7年前 , 10F
for num in ['p','t','t',' ','i','s',' ',......]
11/03 23:28, 10F

11/05 11:08, 7年前 , 11F
感覺好leetcode
11/05 11:08, 11F
文章代碼(AID): #1P_2id-G (Python)