python에서 리스트가 NoneType으로 변합니다
조회수 4424회
VOWELS = "aeiouy"
answer = ''
def translate(phrase):
a = list(phrase)
answer = []
print(type(a))
try:
for i in range(len(a)):
if not a[i] in VOWELS:
answer.append(a[i])
if a[i] != ' ':
a.remove(a[i+1])
if a[i] in VOWELS and a[i-1] == a[i] == a[i+1]:
answer.append(a[i])
a.remove(a[i-1]).remove(a[i]).remove(a[i+1])
return ''.join(answer)
except Exception as ex:
print(x)
translate("hieeelalaooo")
NoneType object has no attribute 'remove'라고 뜨는데 분명히 a를 list로 했는데 왜 None타입이라고 하나요?
2 답변
-
파이썬의 list 에서 remove 메소드의 리턴값은 None 입니다. 즉 리턴값이 없는 메소드입니다.
a.remove(a[i-1]).remove(a[i]).remove(a[i+1])
위와 같은 체인링은 불가능합니다.
아래와 같이 각각 처리해야 합니다.
a.remove(a[i-1]) a.remove(a[i]) a.remove(a[i+1])
-
예외처리를 할 때는 이래와 같이 Exception 의 repr 만 받지 말고 스택트레이스를 이용하세요.
try: ... except Exception as ex: print(x) list index out of range
보다는 아래와 같이 해서 에러 발생 위치까지 알 수 있습니다. print_exc 는 가장 기본적인 형태이고 traceback 모듈에 다양한 기능이 제공됩니다.
import traceback as tb try: ... except Exception as ex: tb.print_exc() Traceback (most recent call last): File "<ipython-input-7-3313462386d7>", line 20, in translate a.remove(a[i+1]) IndexError: list index out of range
댓글 입력