简体   繁体   中英

Convert given input from string to integer or float in python and if the input is string or character it can able handle it?

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'?

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
s = 'aa'

try:
   print int(s)
except ValueError:
   try:
      print float(s)
   except:
      print 'its is a string'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM