Home > Software engineering >  Can elements of a list be split using list comprehension when it involves regex?
Can elements of a list be split using list comprehension when it involves regex?

Time:12-10

An example of using list comprehension to split elements of a list is here: How to split elements of a list?

myList = [i.split('\t')[0] for i in myList] 

Can something like this be done using re.split if you want to split on regex? Simply substituting re.split for split in the above along with regex term yields attribution error:

AttributeError: 'str' object has no attribute 're'

So re is not being recognized as the regex library when used in this form of list comprehension. Can it be done?

CodePudding user response:

With i.split(), you're using a method of the string object itself. If you want to use a function from somewhere else, like re.split() you can't call it on the object itself - it doesn't know about it.

Instead:

import re 

myList = [re.split('\t', i)[0] for i in myList] 

If you read the documentation on re.split, you'll notice that it requires you to pass the string to split as a parameter, instead of operating directly on it.

  • Related