In python, the list changes to NoneType

Asked 2 years ago, Updated 2 years ago, 12 views

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")

It says NoneType object has no attribute "remove" Why do you say "None type" even though "a" is a list?

python

2022-09-21 20:03

2 Answers

In Python's list, the return value of the remove method is None. Method without return value.

a.remove(a[i-1]).remove(a[i]).remove(a[i+1])

The chain ring as above is not possible.

Each should be handled as follows.

a.remove(a[i-1])
a.remove(a[i])
a.remove(a[i+1])


2022-09-21 20:03

When handling exceptions, do not receive only the repr of the exception like this and use the stack trace.

try:
...
except Exception as ex:
        print(x)

list index out of range

Rather, you can find out the location of the error as below. print_exc is the most basic form, and the traceback module provides a variety of features.

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


2022-09-21 20:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.