Python: parseInt implementation similar to JavaScript's parseInt function

There are many scenarios where type conversion from a String to an Integer is required. Occasionally it is convenient to parse-out an element's numeric id named by a schema similar to  'alphanumFIELDNAME_numID' by the readily available integer parsing functions of the scripting language of choice.
Reassuring myself again that Python doesn't provide that Integer-whisperer functionality, nor did the top 10 google results in a satisfying manner.
The background is that, JavaScript's parseInt implementation is rather convenient in handling all input types and useful, as the second argument can be used to set the base of the parsed-Integer, in the success-case.

parseInt(in, base)

Here is a quick example to see how JavaScript's parseInt performs when battered with different input types:



The described JavaScript-like parseInt functions described on stackexchange are non-satisfactory in handling type-diversity resulting in many Exception cases. Additionally in the case of unparsable input-types it would be useful to get a  Not-a-Number or any well discernible result returned.

Find below an approach to the parseInt function, which performs in a more JavaScript-like manner and can be plugged into your Python code as a lambda function:



LihatTutupKomentar