Home > front end >  How to check a data type in python?
How to check a data type in python?

Time:09-09

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"

CodePudding user response:

Brother, 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")

Have a good day

CodePudding user response:

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

CodePudding user response:

What i think is that input takes arguments as string, so you will have to convert it to integer

CodePudding user response:

You can try with inp.isdigit(): comparison to check for integer digits

CodePudding user response:

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

CodePudding user response:

input() method takes arguments as a str, you have to convert it into int()

  • Related