作者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://webptt.com/cn.aspx?n=bbs/Python/M.1467692026.A.A7A.html
1F:→ mikapauli: help(str.index) 看一下吧 07/05 12:55
2F:→ marksmanz: j = [ idx for idx, c in enumerate(x, start = 1) i 07/05 13:04
3F:→ marksmanz: f c == 'a'] 07/05 13:04
4F:→ PHONm: 感谢一楼! 看完解释突然懂了 因为最後找不到值後会引起 07/05 13:18
5F:→ PHONm: error,我以为只是回传None而已@@! 感谢 07/05 13:18
6F:→ PHONm: 用二楼提供的以解决,感谢! 07/05 13:23
7F:推 Yshuan: 我会选择enumerate再filter ... 07/05 15:32
8F:→ uranusjr: 其实你原本的程式改用 find 然後改 != -1 就可以了... 07/05 16:37