3

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

user1539348
  • 513
  • 1
  • 7
  • 20

2 Answers2

5

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

Captain Wise
  • 480
  • 3
  • 13
2

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.