Reputation: 1460
am trying to check if a value in a dictionary is an integer or not.
I have something like
d = {'number' : '1-', 'name' : 'A'}
am trying to see if the value of number is an integer after removing the '-'
Code:
d['number'] = d['number'].replace('-','')
so now its showing me d = {'number' : '1', 'name' : 'A'}
here the value of number is again a string. But i want to check if the string is a number or an alphabet.
number can be of '12121' or 'rdrr'
How do I check if it has only digits ?
Upvotes: 0
Views: 4138
Reputation:
If you need both key and value:
d = {'number' : '1', 'name' : 'A'}
digits = {}
for key, value in d.items():
if value.isdigit():
digits[key] = value
If you need just key:
digits = [key for key, value in d.items() if value.isdigit()]
Result of :
print(digits)
for 1st solution:
{'number': '1'}
for 2nd solution:
['number']
Upvotes: 0
Reputation: 127
You can use isdigit()
and isalpha()
functions. isdigit()
returns "True" if all characters in the string are digits and isalpha()
returns "True" if all characters in the string are alphabetic:
>>> d = {'number' : '1', 'name' : 'A'}
>>> d['number'].isdigit()
True
>>> d['number'].isalpha()
False
>>> d['name'].isdigit()
False
>>> d['name'].isalpha()
True
Upvotes: 1
Reputation: 233
Use the re
module
import re
if re.match(r"\d+","12"): print('It is a number')
Upvotes: 1