简体   繁体   中英

How do I check if an input is a string or int in Python 2.x?

I am trying to check if an input is a word or a number.

var = input("var: ")

if isinstance(var, str):
    print "var = word"

else:
   print "var = number"

This is the code I came up with but sadly doesn't work; I'm new to python and programming in general so I don't know alot of commands, any suggestion would be appreciated ^^

Did you try str.isdigit() ? For example:

v = raw_input("input: ")

if v.isdigit():
    int(v)
    print "int"
else:
    print "string"

input() would always return for you a string ( str type). there are several things you can do with that string to check if it's an int

  1. you can try casting that string to an int:

     var = input("var: ") try: var = int(var) except ValueError: print "var is a str" print "var is an int" 
  2. you can use regular expression to check if the string contains only digits (if your int is decimal, for other bases you'd have to use the appropriate symbols):

     import re var = input("var: ") if re.match(r'^\\d+$', var): print "var is an int" else: print "var is a str" 

To check the variable type you can do the following:

>>> x = 10
>>> type(x)
<type 'int'>

For string:

>>> y = "hi"
>>> type(y)
<type 'str'>

Using isinstance :

x = raw_input("var: ")
try:
    int(x)
except ValueError:
    print "string"
else: 
    print "int"

input() will take and evaluate your input before handing it over to you. That is, if the user enters exit() , your application will exit. This is undesirable from a standpoint of security. You would want to use raw_input() instead. In this case you can expect the returned value to be a string.

If you still want to check if the strings content is convertible to a (integer) number, please follow the approach discussed here:

A short outline: Just try to convert it to a number and see if it fails.

Example (untested):

value = raw_input()
try:
    int(value)
    print "it's an integer number"
except ValueError:
    print "it's a string"

For reference:

Note that the semantics of the input() function change with Python 3:

As @paidhima said the input function will always return a string in python 3.x. Example:

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> var = input("var: ")
var: 12
>>> var
'12'
>>>type(var)
<class 'str'>
>>> 

If i do the following:

>>> var = input("var: ")
var: aa
>>> var
'aa'
>>> type(var)
<class 'str'>
>>>

They are both string because it is not a good idea to have the program decide if it's gonna give us a string or and integer, we want the logic that we build in the program to handle that. In python3.x you example is not gonna work, but you can try this this:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

var = input('var: ')

# we try to conver the string that we got
# in to an intiger 
try:
    # if we can convert it we store it in the same
    # variable
    var = int(var)
except ValueError:
    # if we can't convert we will get 'ValueError'
    # and we just pass it 
    pass


# now we can use your code 
if isinstance(var, str):
    print("var = word")

else:
    print("var = number")
# notice the use of 'print()', in python3 the 'print is no longer 
# a statement, it's a function

Now back to your script using python2.x. As i said above it's not a good practice to use the function input , you can use raw_input that works the same in python2.x like input in python3.x .

I'm gonna say it again because i don't want to confuse you : Python2.x:

input 
# evaluates the expression(the input ) and returns what
# can make from it, if it can make an integer it will make one
# if not it will keep it as a string

raw_input
# it will always return the expression(the input ) as a string for 
# security reasons and compatibility reasons

Python3.x

 input
 # it will always return the expression(the input ) as a string for 
 # security reasons and compatibility reasons

Attention, in python3.x there is no raw_input .

Your code should work just fine, in python2.x, make sure you use the right python, and i hope this helped you in a way or another.

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