作者PHONm (USA~USA)
看板Python
標題[問題] ValueError: substring not found
時間Tue Jul 5 12:13:44 2016
我想要把所有'a'的index找出,我知道有正規畫表示法,
但在自己在試寫的時候出現了下面問題,請幫忙解惑,感謝大家!
x = 'An apple a day, keeps the doctor away'
i= 0
j = []
while x.index('a',i) is not None:
i = x.index('a',i) + 1
j.append(x.index('a',i))
print(j) #如果這邊往左移,不放在while迴圈內則會不顯示j序列,不知道為什麼@@!
----------------------------------------------------------------------------
Out:
[9]
[9, 12]
[9, 12, 33]
[9, 12, 33, 35]
Traceback (most recent call last):
File "C:/Users/cash.chien/PycharmProjects/element_number/test.py", line 7,
in <module>
j.append(x.index('a',i))
ValueError: substring not found
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.131.189
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1467692026.A.A7A.html
→ mikapauli: help(str.index) 看一下吧 07/05 12:55
→ marksmanz: j = [ idx for idx, c in enumerate(x, start = 1) i 07/05 13:04
→ marksmanz: f c == 'a'] 07/05 13:04
→ PHONm: 感謝一樓! 看完解釋突然懂了 因為最後找不到值後會引起 07/05 13:18
→ PHONm: error,我以為只是回傳None而已@@! 感謝 07/05 13:18
→ PHONm: 用二樓提供的以解決,感謝! 07/05 13:23
推 Yshuan: 我會選擇enumerate再filter ... 07/05 15:32
→ uranusjr: 其實你原本的程式改用 find 然後改 != -1 就可以了... 07/05 16:37