Filter strings that have a symbol appear certain times

Viewed 54

How to make a condition that accepts only in a loop strings that have '_' only two times.

a = ['q_s_e','s_e_v_e','s_v']# many more like these

in the above list only the fist item should used in the loop:

for i in a:
    if '_' in i:
         ...

this takes everything.

How to do it?

5 Answers

You can use the count function from string:

a = ['q_s_e','s_e_v_e','s_v']
for i in a:
    if i.count('_') == 2:
      print ('hooray')

In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

The syntax of count() method is:

string.count(substring, start=..., end=...)

Another way is to filter the array of string at the beginning as well:

a = ['q_s_e','s_e_v_e','s_v']
for i in filter(lambda k: k.count('_') == 2, a):
    print ('hooray')

You can use str.count and iterate over a generator expression:

for i in (el for el in a if el.count('_') == 2):
    # do something

You need to specify that with a conditional using the count() method:

for item in list:
    if item.count('_') == 2:
        ...

Use regex, this will return the list you want:

filtered_list = [e for e in old_list if re.match('^[^_]*(_[^_]*){2}$', e)]

Regex ^[^_]*(_[^_]*){2}$ will make sure each of these element contains exactly 2 _

You can also solve this with numpy and remove your loop:

arr = np.array(['q_s_e','s_e_v_e','s_v'])
new_arr = arr[np.where(np.char.count(arr, "_") == 2)[0]]
Related