Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: converting string to flags

If I have a string that is the output of matching the regexp [MSP]*, what's the cleanest way to convert it to a dict containing keys M, S, and P where the value of each key is true if the key appears in the string?

e.g.

 'MSP' => {'M': True, 'S': True, 'P': True}
 'PMMM'   => {'M': True, 'S': False, 'P': True}
 ''    => {'M': False, 'S': False, 'P': False}
 'MOO'    won't occur... 
          if it was the input to matching the regexp, 'M' would be the output

The best I can come up with is:

 result = {'M': False, 'S': False, 'P': False}
 if (matchstring):
     for c in matchstring:
         result[c] = True

but this seems slightly clunky, I wondered if there was a better way.

like image 887
Jason S Avatar asked Jul 14 '26 20:07

Jason S


1 Answers

Why not use a frozenset (or set if mutability is needed)?

s = frozenset('PMMM')
# now s == frozenset({'P', 'M'})

then you can use

'P' in s

to check whether the flag P exists.

like image 172
kennytm Avatar answered Jul 16 '26 10:07

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!