0

Hello does anybody know how I identify if an input is a string or int

I want to make a code that gives a certain output if you input a string

19th Oct 2019, 5:57 PM
Mine Minecrafft
Mine Minecrafft - avatar
8 ответов
+ 2
Mine Minecrafft, if you are using: inp = int(input('Enter a number')) and user does input 4 5, int conversion will fail and you will get a ValueError. To avoid this, you should put your relevant code in a try ... except ... block.
19th Oct 2019, 7:18 PM
Lothar
Lothar - avatar
+ 6
An input is *always* string. But you can check if it's convertible to int or not. inp=input() try: int(input) except: ... # If we get here # it was not an int
19th Oct 2019, 6:06 PM
HonFu
HonFu - avatar
+ 4
The point is, as I have written: The type of input is automatically ALWAYS string.
19th Oct 2019, 6:20 PM
HonFu
HonFu - avatar
+ 4
Python input function always gives back a string, no matter what characters are entered. But the content of this string can be meant as text or number. This can be checked by using the several string methods. inp = input('Your name please:') # <- user enters 'John' if inp.isalpha(): # <- checks for alphabetical characters ... num = input('Enter number:') # < user enters 16 If num.isdigit(): # <- checks for digits ... There are also some other methods for checking: isalnum(), isspace(),... Keep in mind, that input can be a mix of the mentioned characters.
19th Oct 2019, 6:22 PM
Lothar
Lothar - avatar
+ 1
Thanks for giving me the code I looked for but If i put an int(input()) or a float(input()) it becomes an int or float in an input() yes that is string but it can't be an int
19th Oct 2019, 6:26 PM
Mine Minecrafft
Mine Minecrafft - avatar
+ 1
Int are numbers string are text surely you can write numbers in a text module but it won't be seen as an int and you cant write text in int either
19th Oct 2019, 6:28 PM
Mine Minecrafft
Mine Minecrafft - avatar
+ 1
Thanks that really helped
19th Oct 2019, 10:57 PM
Mine Minecrafft
Mine Minecrafft - avatar
0
I remember that on Idle and on reple.it you culd use a float(input()) to input both string and int but it does not work here so that is also a problem but the main question is still how do I define a string Do I write If inp= str:
19th Oct 2019, 6:16 PM
Mine Minecrafft
Mine Minecrafft - avatar