Attempting to find all occurrences of characters
string1 = '%(example_1).40s-%(example-2)_-%(example3)s_'
so that output has all occurrences of '-' '_' not in parentheses
['-', '_', '-', '_']
Do not need to care about nested parentheses
Attempting to find all occurrences of characters
string1 = '%(example_1).40s-%(example-2)_-%(example3)s_'
so that output has all occurrences of '-' '_' not in parentheses
['-', '_', '-', '_']
Do not need to care about nested parentheses
You can use module re
to do that by passing regex to it
import re
str = '%(example_1).40s-%(example-2)_-%(example3)s_'
#remove all occurences of paratheses and what is inside
tmpStr = re.sub('\(([^\)]+)\)', '', str)
#take out other element except your caracters
tmpStr = re.sub('[^_-]', '', tmpStr)
#and transform it to list
result_list = list(tmpStr)
Result
['-', '_', '-', '_']
And like Bharath shetty has mentioned it in comment, do not use str
, it's a reserved word in python for built-in strings
The following will give you your output.:
>>> import re
>>> str = '%(example_1).40s-%(example-2)_-%(example3)s_'
>>> print list("".join(re.findall("[-_]+(?![^(]*\))", str)))
['-', '_', '-', '_']
What this does is it finds all the substrings containing '-'
and/or '_'
in str
and not in parentheses. Since these are substrings, we get all such matching characters by joining, and splitting into a list.