How to coerce a list of vars into a new type?

vbgunz vbgunz at gmail.com
Mon Oct 2 14:35:45 EDT 2006


> I want to verify that three parameters can all be converted into
> integers, but I don't want to modify the parameters themselves.

You can twist and tweak this version OR completely redo it. In this
version a list of the conversions are returned *but* if you want to
only check if such a conversion can be made, you can return a bool
result instead of the list. Also integers are converted to floats. just
wrap the float() in an int() if you only want ints instead and wrap
again with round() or mix and do as you please to get the results you
want.


def convertToInteger(*args):
  ''' try to convert arguments to integers and return them in a list'''

  try:
    return [float(x) for x in (args)]
  except ValueError:
    print 'convertToInteger: pass compatible args OR return a default!'
    return


funcResult = convertToInteger('1', '2', '3')
if funcResult:  # if conversion was perfect, choose to do what you want
  # ...
  a, b, c = funcResult  # change global variables!
  x, y, z = funcResult  # create three new variables!
  print a, b, c
  print x, y, z
  # ...




More information about the Python-list mailing list