How to check input() data type in python?

Question:

I am trying to check a data type in python.
I want to use an if statement to check if the data is a string or not. And everytime i input an integer it returns the value as a string.

Here is the code.

inp = input("Input: ")

if type(inp) != str:
    print("You must input a string")
else:
    print("Input is a string")

this is the message it returns.

Input is a string

I want it to print "You must input a string"

Asked By: SJXD

||

Answers:

It will always be a string as input() captures the text entered by the user as a string, even if it contains integers.

Answered By: Magnum

First of all numbers can also be strings. Strings are anything which is enclosed in double quotes. Anyway if all you need is to get an input and verify that it’s not a number you can use:

inp = input("Input: ")

if inp.isdigit():
    print("You must input a string")
else:
    print("Input is a string")

Or if you wish to have a string with no digits in it the condition will go something like this:

inp = input("Input: ")

if any(char.isdigit() for char in inp) :
    print("You must input a string")
else:
    print("Input is a string")
Answered By: Dhaivath Lal

The input() function always returns a datatype of string. To check if what you want to check a simple way would be to iterate over the string and if there is no character present then print "You must input a string".

inp = input("Input: ")
for i in inp:
    if i.isalpha():
        print("Input is a string")
        break
else:
    print("You must input a string")

A better solution would be using try except:

inp = input("Input: ")

try:
    x=int(j)
    print("You must input a string")
except:
    print("Input is a string")

this is because int() function throws an error of there is a letter in the string given to it as an input parameter

Answered By: Woundrite
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.