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

别来无恙 提交于 2020-01-06 02:41:05

问题


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 ^^


回答1:


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:

  • How do I check if a string is a number (float) in Python?

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:

  • https://docs.python.org/2/library/functions.html#int
  • https://docs.python.org/2/library/functions.html#input
  • https://docs.python.org/2/library/functions.html#raw_input

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

  • https://docs.python.org/3/library/functions.html#input



回答2:


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

v = raw_input("input: ")

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



回答3:


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"
    



回答4:


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"



回答5:


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.



来源:https://stackoverflow.com/questions/28486058/how-do-i-check-if-an-input-is-a-string-or-int-in-python-2-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!