Python Style Question

Denis McMahon denismfmcmahon at gmail.com
Fri Oct 31 05:55:30 CET 2014


On Fri, 31 Oct 2014 09:48:10 +1100, Steven D'Aprano wrote:

> MRAB wrote:

>> How about:
>> 
>> int(str(obj).strip('"'))
> 
> Absolutely not.
> 
> obj = '""""""""""""""1\n\n\n\n'  # not valid JSON load_int(obj)
> => raises ValueError int(str(obj).strip('"'))
> => wrongly returns 1

How about

#!/usr/bin/python

import re, json

l = [1, -1, 0, '+2', '2', '-2', '0', '"+3"', '"3"', '"-3"', '"0"', 
     json.dumps(-4), json.dumps(4), json.dumps(0), 
     'x', 'sqjklsqjk__', (5, 6), 
     7.7, -7.7, '8.8', '+8.8', '-8.8', '"9.9"', '"+9.9"', '"-9.9"']

patt1 = re.compile(r'^([-+]?\d+)$')
patt2 = re.compile(r'^"([-+]?\d+)"$')

def getTheInt(x):

    if isinstance(x,int):
        return x

    if isinstance(x,str):
        tmp = patt1.match(x)

        if tmp:
            return int(tmp.group(1))

        tmp = patt2.match(x)

        if tmp:
            return int(tmp.group(1))

    return None

a = []

for n in l:
    a.append(getTheInt(n))

print a

# end of code

prints:

[1, -1, 0, 2, 2, -2, 0, 3, 3, -3, 0, -4, 4, 0, None, None, None, None, 
None, None, None, None, None, None, None]

I know re matching the strings may be overkill, but it may be the best 
way of checking that the string contains the expected character format to 
convert to an int.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list