Filter strings that have a symbol appear certain times

2865 views python
1

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?

answered question

1 Answer

2

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')

posted this

Have an answer?

JD

Please login first before posting an answer.