문제

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