Reputation: 740
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
Upvotes: 2
Views: 357
Reputation: 7867
To gain more control, esp in case if you have some type of strings which inbuilt functions don't support, you can use re -
A regular exp like below to check if its a number -
re.findall(r'^[-]?[0-9]*[\.]?[0-9]*$', s)
and the following regular exp to check if its a string -
r'^[a-zA-Z]+$'
Please note that this is just for demo, you should modify the regular exp as per your needs.
Upvotes: 0
Reputation: 363043
To implement the logic your asking for, I guess the most pythonic way would be to use exception handling:
try:
n = int(random_string)
except ValueError:
if len(random_string) > 1:
# it's a word
else:
# it's a character (or the empty string)
To check the case, you can use the string method islower()
.
Upvotes: 2
Reputation: 251428
Strings have methods isalpha
and isdigit
to test if they consist of letters and digits, respectively:
>>> 'hello'.isalpha()
True
>>> '123'.isdigit()
True
Note that they only check for those characters, so a string with spaces or anything else will return false for both:
>>> 'hi there'.isalpha()
False
However, if you want the value as a number, you're better off just using int
. Note that there's no point checking with isinstance
whether the result is indeed an integer. If int(blah)
succeeds, it will always return an integer; if the string doesn't represent an integer, it will raise an exception.
Upvotes: 4
Reputation: 798944
Take your pick.
>>> '4'.isdigit()
True
>>> '-4'.isdigit()
False
>>> int('-4')
-4
>>> 'foo'.isdigit()
False
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
Upvotes: 2