Code: Alles auswählen
>>> isint("- 1")
False
>>> int("- 1")
-1
>>> isint(" -1")
False
>>> int(" -1")
-1
>>> isint(" 1")
False
>>> int(" 1")
1
Code: Alles auswählen
>>> isint("- 1")
False
>>> int("- 1")
-1
>>> isint(" -1")
False
>>> int(" -1")
-1
>>> isint(" 1")
False
>>> int(" 1")
1
Code: Alles auswählen
#!/usr/bin/env python
#-*- coding: iso-8859-1 -*-
import re
a = ('','foo 30','.20','20.',',20','20,','1.3E2', '2..3','++3','2.3.',
'10','..3','0','100','100.23','1,100.23','-3E-2', "- 15.3", " 24.32 ", "+ 32. ", " - 21,23 ", "-.", "-")
patobj = re.compile("^ *[+-]? *(\d+|\d+\.\d*|\d*\.\d+) *$")
for i in a:
if patobj.search(i):
print i + " is True."
else:
print i + " is False."
try:
b = float(i)
print i + " is Good."
except:
print i + " is Bad."
print
Außerdem lasse ich meine Anwendung sich wenn möglich nicht vorsätzlich aufhängen (try: ... except: ....), vor allem wenn ich meinen Code auch mal in andere Sprachen bringen will, die das nicht unterstützen.>>USe an eval, it's correct (by definition) and avoids possible errors
>QA Editors note: This solution doesn't work as described.
try-except ist bei Python allerdings vollkommen üblich und sogar ausdrücklich erwünscht (Stichwort: EAFP).problembär hat geschrieben:Außerdem lasse ich meine Anwendung sich wenn möglich nicht vorsätzlich aufhängen (try: ... except: ....), vor allem wenn ich meinen Code auch mal in andere Sprachen bringen will, die das nicht unterstützen.
Ist soweit nicht unvollständig. Bei den Leerzeichen war ich nur etwas großzügig. Das heißt, vor der Umwandlung in float muß man noch die Leerzeichen rausziehen:und unvollständig
Code: Alles auswählen
#!/usr/bin/env python
#-*- coding: iso-8859-1 -*-
import re
a = ('','foo 30','.20','20.',',20','20,','1.3E2', '2..3','++3','2.3.',
'10','..3','0','100','100.23','1,100.23','-3E-2', "- 15.3", " 24.32 ", "+ 32. ", " - 21,23 ", "-.", "-")
patobj = re.compile("^ *[+-]? *(\d+|\d+\.\d*|\d*\.\d+) *$")
for i in a:
if patobj.search(i):
print i + " is True."
i = i.replace(" ", "")
i = float(i)
print "Type of i is now: " + str(type(i))
else:
print i + " is False."
print