Oct-06-2019, 06:16 AM
(This post was last modified: Oct-06-2019, 06:16 AM by Gribouillis.)
adt Wrote:Would there be any objection if a similar built-in function were to get incorporated in python too ?I don't have an objection but I'm not in charge of the contents of the standard library. Why do you need the function to be built-in? You can very well design a separate library that contains this. Here is an example, I don't say it's the best way to do it, a pure regex implementation may be better.
import ast import re from tokenize import generate_tokens, NUMBER import io def func(s): t = re.sub(r'\s+', '', s) f = io.StringIO(t) for tok in generate_tokens(f.readline): if tok[0] == NUMBER: return ast.literal_eval(tok[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), ] for inp, out in sample: assert out == func(inp)It won't work with complex numbers however. Also it needs to be changed if there is a sign + or - in front of the number. How does the Val function handle a sign?