How to find characters not in parentheses
2 answers
Below is your output:
>>> import re
>>> str = '%(example_1).40s-%(example-2)_-%(example3)s_'
>>> print list("".join(re.findall("[-_]+(?![^(]*\))", str)))
['-', '_', '-', '_']
What this means is, it finds all substrings containing '-'
and / or '_'
in str
, not in parentheses. Since these are substrings, we get all such matching characters by concatenating and parsing into a list.
+2
source to share
You can use a module re
to do this by passing a regular expression 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 as Bharath shetty mentioned in a comment, don't use str
, it is a reserved word in python for inline strings
+5
source to share