0

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() 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.

Community
  • 1
  • 1
rhormaza
  • 487
  • 1
  • 4
  • 9

5 Answers5

1

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
bikeshedder
  • 7,337
  • 1
  • 23
  • 29
0

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!
Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
0
some_dict = dict(mString1=1, mString2=2, mString3=3)
return some_dict.get(string_value, 0)

Where string_value is one of mString1, mString2, mString3.

UnLiMiTeD
  • 1,000
  • 1
  • 9
  • 17
0
mylist = ['mString1', 'mString2', 'mString3', 'mString4']
retVal = [i for i in range(len(mylist)) if mylist[i] = mStrVar][0] + 1
f p
  • 3,165
  • 1
  • 27
  • 35
0
retval, = [i for i in xrange(1, 5) if 'mString%s' % i in mStrVar] or [0]
Rich Tier
  • 9,021
  • 10
  • 48
  • 71