Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Denis McMahon Newsgroups: comp.lang.python Subject: Re: Python Style Question Date: Fri, 31 Oct 2014 04:55:30 +0000 (UTC) Organization: A noiseless patient Spider Lines: 66 Message-ID: References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> <5452c02a$0$12994$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injection-Date: Fri, 31 Oct 2014 04:55:30 +0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="66ffcfa4470a58bcddbdcd1913f98ab4"; logging-data="23214"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+CYme1yzcnCd38g+LsgfshKCXMG8ZlGio=" User-Agent: Pan/0.136 (I'm far too busy being delicious; GIT 926a150 git://git.gnome.org/pan2) Cancel-Lock: sha1:Z7i+hxEKqnT5TKU/GwrtBJtfJV0= Xref: csiph.com comp.lang.python:79998 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@gmail.com