In my python code, I wanted to check if a string contains a number. With Perl, regex is the way for this. With Python, I could check each character in the given string using method isdigit(), and use built-in function any() to obtain the desired result. Here's how.
>>> def containsNumber(inputString):
... return any(char.isdigit() for char in inputString)
...
>>> containsNumber("hi there")
False
>>>
>>> containsNumber("hi there you three")
False
>>>
>>> containsNumber("hi there 3 of you")
True
>>>
>>> containsNumber("hi there 3.5 of you")
True
>>>
>>> containsNumber("hi there -3.5 of you")
True
>>>
>>> containsNumber("Once I saw 1024 trees")
True
>>>
>>> containsNumber("Once I saw 1024 trees and 256 of them were binary")
True
>>>>>> containsNumber("5000")
True
>>>
>>> def containsNumber(inputString):
... return any(char.isdigit() for char in inputString)
...
>>> containsNumber("hi there")
False
>>>
>>> containsNumber("hi there you three")
False
>>>
>>> containsNumber("hi there 3 of you")
True
>>>
>>> containsNumber("hi there 3.5 of you")
True
>>>
>>> containsNumber("hi there -3.5 of you")
True
>>>
>>> containsNumber("Once I saw 1024 trees")
True
>>>
>>> containsNumber("Once I saw 1024 trees and 256 of them were binary")
True
>>>>>> containsNumber("5000")
True
>>>
No comments:
Post a Comment