All the values are of course "actual strings" (you can do with them all you can possibly do with strings!), but I think most respondents know what you mean -- you want to try converting each value to several possible types in turn ('int' then 'float' is specifically what you name, but couldn't there be others...?) and return and use the first conversion that succeeds.
This is of course best encapsulated in a function, away from your application logic. If the best match for your needs is just to do the conversion and return the "best converted value" (and they'll all be used similarly), then:
def best_convert(s, types=(int, float)):
for t in types:
try: return t(s)
except ValueError: continue
return s
if you want to do something different in each case, then:
def dispatch(s, defaultfun, typesandfuns):
for t, f in typesandfuns:
try:
v = t(s)
except ValueError:
continue
else:
return f(v)
return defaultfun(s)
to be called, e.g, as
r = dispatch(s, asstring, ((int, asint), (float, asfloat)))
if the functions to be called on "nonconvertible strings", ones convertible to int, and ones convertible to float but not int, are respectively asstring, asint, asfloat.
I do not recommend putting the "structural" "try converting to these various types in turn and act accordingly" code in an inextricable mixture with your "application logic" -- this is a clear case for neatly layering the two aspects, with good structure and separation.