0

Is there a Python function which converts a screen/console input as for example 10**8 to the integer 100000000. This would save typing all those zeros with the possibility of error.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Arnold
  • 153
  • 1
  • 9
  • 1
    `eval("10**8")`? – Frank Dec 02 '18 at 22:19
  • 2
    Use scientific notation, e.g. `s = '1e8'`, and then evaluate it as `int(float(s))` (but it only works for n=10, and for x up to 22). – Warren Weckesser Dec 02 '18 at 22:19
  • 1
    @Frank Better use `ast.literal_eval` for evaluating user-input. – tobias_k Dec 02 '18 at 22:25
  • 1
    @tobias_k fails for this input though (by itself) – Chris_Rands Dec 02 '18 at 22:27
  • Underscores can help readability: `int('100_000_000')`. – 101 Dec 02 '18 at 22:30
  • IMO the proper answer is to write a parser https://stackoverflow.com/a/9558001/6260170 – Chris_Rands Dec 02 '18 at 22:31
  • 1
    @tobias_k Thank you so much I didn't know `ast.literal_eval` before. However I tried it and as @Chris_Rands said it didn't work. I checked the docs and it only works with `strings, numbers, tuples, lists, dicts, booleans, and None.` https://docs.python.org/2/library/ast.html#ast.literal_eval – Frank Dec 02 '18 at 22:33
  • @tobias_k: As Frank already pointed out, `ast_literal()` won't work for this—but the more relevant line in its [documentation](https://docs.python.org/3/library/ast.html#ast.literal_eval) is "It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing." – martineau Dec 02 '18 at 23:04

1 Answers1

3

these are two possible solutions:

inp = "10**8"

a = eval(inp) #don't use eval for untrusted input
b = int(inp.split("**")[0])**int(inp.split("**")[1])

print (10**8 == a == b)

output:

True

Liam
  • 6,009
  • 4
  • 39
  • 53