0

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?

jub
  • 377
  • 1
  • 2
  • 14
  • "So re is not being recognized as the regex library when used in this form of list comprehension. Can it be done?" what are you talking about? What form? Are you literally doing `i.re.split('\t')`? Why do you think that would work? What library works like that? That never works anywhere, a list comprehension has nothing to do with it. Have you read the [docs](https://docs.python.org/3/library/re.html) or the helpful [HOWTO](https://docs.python.org/3/howto/regex.html#regex-howto)? – juanpa.arrivillaga Dec 09 '21 at 02:26

1 Answers1

4

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.

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • You're welcome - if it answers your question, feel free to click the check mark underneath the vote counter, to indicate that the question no longer require answers. – Grismar Dec 09 '21 at 03:31