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 '#'?

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top