Question: I'm refactoring some scripts that have a bunch of code with like this:

```
if 'mString1' in mStrVar:
    retVal = 1
elif 'mString2' in mStrVar:
    retVal = 2
elif 'mString3' in mStrVar:
    retVal = 3
elif 'mString4' in mStrVar:
    retVal = 4
else:
    retVal = 0

```

Personally I don't like this I always prefer the [`dict()`](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python!) approach, but in this specific case, I think, I cannot be done in that way.

is it possible to rewrite this in a more short way? `mString` goes around `mString10` in some cases.

Any hints highly appreciated, and apologies if this is a duplicated I couldn't find any question related.

Answer: 
You could create a mapping list and use a plain for loop to search for the strings in the `mStrVar` variable:

```
retVal_mapping = [
   ('mString1', 1),
   ('mString2', 2),
   ('mString3', 2),
   ('mString4', 2),
   ('', 0) # default as "'' in anyString" is always true.
]

for s, retVal in retVal_mapping:
    if s in mStrVar:
        break

# retVal now contains the right value

```
If you would for example use the regular expression `mString(\d+)` you can do this:

```
# Precompile pattern into finite automaton:
_pattern = re.compile(r'mString(\d+)')

# Apply multiple times.
match = _pattern.match(mStrVar)
if match:
    retVal = int(match.group(1))
else:
    retVal = 0

```

The problem with your substring-code above is that it is not very well defined if e.g.
`mStrVar = "mString1mString2mString3mString4"`. The regular expression matching is actually much stricter, which may be desired.

You can do a `dict` style approach, too, for non-numeric patterns:

```
# Precompile pattern:
_pattern = re.compile(r'(abc|def|ghi)')
_map = { 'def' : 1, 'ghi' : 2, 'abc' : 3 }

match = _pattern.match(mStrVar)
if match:
    retVal = _map.get(match.group(1), 0)
else:
    retVal = 0

```

in some cases, you can just use the dict right away, too:

```
_map = { 'def' : 1, 'ghi' : 2, 'abc' : 3 }
retVal = _map.get(mStrVar, 0) # 0 is default!

```