Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct Try Exception for NoneType when using regex's .groups() function

Tags:

People also ask

How do you except NoneType errors in Python?

One way to avoid this error is to check before iterating on an object if that object is None or not. Another way to handle this error is to write the for loop in try-except block. The third way is to explicitly assign an empty list to the variable if it is None . Host your Django Application for free on PythonAnyWhere.

How do I fix NoneType has no attribute in Python?

The Python "AttributeError: 'NoneType' object has no attribute 'replace'" occurs when we try to call the replace() method on a None value, e.g. assignment from function that doesn't return anything. To solve the error, make sure to only call replace() on strings.

What is NoneType error in Python?

NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None . That usually means that an assignment or function call up above failed or returned an unexpected result.

How does Python handle NoneType?

Technically, you can prevent the NoneType exception by checking if a value is equal to None using is operator or == operator before you iterate over that value. To solve the NoneType error, ensure that any values you try to iterate over should be assigned an iterable object, like a string or a list.


I'm trying to use the following code:

try:
    clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups())
except TypeError:
    clean = ""

However I get the following traceback...

Traceback (most recent call last):
  File "test.py", line 116, in <module>
    clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups())
AttributeError: 'NoneType' object has no attribute 'groups'

What is the correct exception / correct way around this problem?