(Oct-06-2019, 08:51 AM)buran Wrote: It's better to use ast.literal_eval as it is safer compared to eval
Thanks buran, for your kind suggestion. Noted for future use.
It is seen that ast.literal_eval() too, throws error in case of mixed strings.
(Oct-06-2019, 08:56 AM)Gribouillis Wrote: If there is still an error, please give full bug report!
Test results for the latest version of func() are placed below:
import ast import re from tokenize import generate_tokens, NUMBER #import io def func(s): t = re.sub(r'\s+', '', s) sign = True for tok in generate_tokens(iter([t, '']).__next__): if sign and tok[1] in ('-', '+'): sign = False continue if tok[0] == NUMBER: return ast.literal_eval(t[:tok[3][1]]) return 0 return 0 if __name__ == '__main__': sample = [ ("45", 45), ("4.5", 4.5), ("4.5ABC", 4.5), ("ABCD", 0), ("AB45", 0), (" 2 45 7 ", 2457), (" 2 4 . 5 7 ", 24.57), ("+4.5", 4.5), ("-4.5", 4.5), # AssertionError (see Error Box) ] for inp, out in sample: assert out == func(inp) print(func(inp))
Output:45
4.5
4.5
0
0
2457
24.57
4.5
Error For Last String "-4.5"Error:Traceback (most recent call last):
File "J:\AdtPython-Practice\00-RoughTesting.py", line 92, in <module>
assert out == func(inp)
AssertionError
A.D.Tejpal