Given this string
random_string= '4'
i want to determine if its an integer, a character or just a word
i though i could do this
test = int(random_string)
isinstance(test,int) == True
but i realized if the random_string does not contain a number i will have an error
basically the random_string can be of the forms
random_string ='hello'
random_string ='H'
random_string ='r'
random_string ='56'
anyone know a way to do this, kind of confused, for determine is its a character what i did was
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
random_string in chars == True
i did another string to check if it was a lowercase letter.
also to check if its a word, i took the length of the string, if the length is more than one i determine that it is a word or a number
issue is how can i check if its a word or a number
please help
Strings have methods
isalphaandisdigitto test if they consist of letters and digits, respectively:Note that they only check for those characters, so a string with spaces or anything else will return false for both:
However, if you want the value as a number, you’re better off just using
int. Note that there’s no point checking withisinstancewhether the result is indeed an integer. Ifint(blah)succeeds, it will always return an integer; if the string doesn’t represent an integer, it will raise an exception.