Question

I have the following code that reads in a file and stores the values into a list. It also reads each line of the file and if it sees a '(' in the file it splits it and everything that follows it on the line.

with open('filename', 'r') as f: 
    list1 = [line.strip().split('(')[0].split() for line in f]

Is there a way that I can change this to split not only at a '(' but also at a '#'?

Was it helpful?

Solution

Use re.split.

With a sample of your data's format, it may be possible to do better than this, but without context we can still show how to use this with the code you have provided.

To use re.split():

import re
with open('filename', 'r') as f:
    list1 = [re.split('[(#]+', line.strip())[0].split() for line in f]

Notice that the first parameter in re.split() is a regular expression to split on, and the second parameter is the string to apply this operation to.

General idea from: Splitting a string with multiple delimiters in Python

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top