-1

inputs: 'aa', '22', '2.45'

input ='22'
try:
   print int(input)
except ValueError:
   print float(input)

How to handle the above code when the input is 'aa' or 'example'?

Ma0
  • 15,057
  • 4
  • 35
  • 65
rmk_pyth
  • 1
  • 5

3 Answers3

2

I think that the simplest way to handle this is to check if the input string is numeric first:

https://www.tutorialspoint.com/python/string_isnumeric.htm

if input.isnumeric():
    print int(input)
else:
    try
        print float(input)
    except ValueError:
        # Do nothing

However if you can avoid exceptions completely the code would be better - exception handling can be quite expensive.

This answer to testing for an integer explains why exception handling can be expensive: https://stackoverflow.com/a/9859202/8358096

To avoid the second exception being hit regularly you could use the isalpha function mentioned below.

if input.isnumeric():
    print int(input)
else:
    if not input.isalpha():
        try
            print float(input)
        except ValueError:
            # Do nothing
L McClean
  • 340
  • 1
  • 8
0
s = 'aa'

try:
   print int(s)
except ValueError:
   try:
      print float(s)
   except:
      print 'its is a string'
MBT
  • 21,733
  • 19
  • 84
  • 102
rmk_pyth
  • 1
  • 5
  • 2
    An explanation, what the posted code does and how this addresses the problem in the question, rarely fails to improve an answer. – MBT Dec 18 '18 at 19:41
  • This code handle string. the previous code does not allow characters or string. – rmk_pyth Dec 18 '18 at 20:09
0

You should use str.isalpha

The only time this breaks in cases like input = 'a2'.

inputs = ['aa','22','2.45']

for input in inputs:
   if not input.isalpha():
      try:
         print int(input)
      except ValueError:
         print float(input)
Levente Vig
  • 1
  • 1
  • 2