Reputation: 566
I'm using python and I have a string variable foo = " I have 1 kilo of tomatoes "
What I want is to check if my string contains an integer (in our case 1 ) and return the specific integer
I know I can use the isdigit function like :
def hashnumbers(inputString):
return any(char.isdigit() for char in inputString)
But it returns true or false and does not store the number . I would appreciate your help . Thank you in advance .
Upvotes: 1
Views: 3569
Reputation: 424
Your question is a little unclear, but I've assumed the following:
If that's right, this code should work:
def hashnumbers(inputString):
num = False
for i in inputString:
if i.isdigit():
num = True
print(i)
return num
However, if I've misunderstood what functionality you're looking for, let me know and I'll amend this.
I hope this helps.
Upvotes: 2
Reputation: 54148
List Comprehension
: Return the digits
To return the digits, use a list comprehension with if
def hashnumbers(inputString):
return [char for char in inputString if char.isdigit()]
print(hashnumbers("super string")) # []
print(hashnumbers("super 2 string")) # ['2']
print(hashnumbers("super 2 3 string")) # ['2', '3']
Return a default value if no digits found (empty list is evaluated as False)
return [char for char in inputString if char.isdigit()] or None
Regex version with re.findall
return re.findall(r"\d", inputString)
return re.findall(r"\d", inputString) or None
Return first one only
def hashnumbers(inputString):
return next((char for char in inputString if char.isdigit()), None)
print(hashnumbers("super string")) # None
print(hashnumbers("super 2 string")) # 2
print(hashnumbers("super 2 3string")) # 2
Upvotes: 5