Reputation: 11
I am trying to write a python script that validates if an input number is the required length, for example the input number has to be : 1234567890. The script should check that it is indeed 10 digits long. I could not find any examples of this.
The checked number is taken from a file.
Upvotes: 1
Views: 1605
Reputation: 28036
if len( str( int( input_variable) ) ) != 10:
fire_milton(burn_this_place_down=True)
Upvotes: 0
Reputation: 33092
Math - if you need the int anyway:
10**10 <= int('12334567890') < 10**11
Upvotes: 1
Reputation: 500317
One way to do this is using regular expressions:
In [1]: import re
In [2]: s = '1234567890'
In [3]: re.match(r'^\d{10}$', s)
Out[3]: <_sre.SRE_Match object at 0x184f238>
In [4]: re.match(r'^\d{10}$', '99999')
The above regex ensures that the string consists of exactly ten decimal digits and nothing else. In this example, re.match
returns a match object if the check passes or None
otherwise.
Upvotes: 2
Reputation: 798606
If it's taken from a file then it's a string.
>>> len('1234567890') == 10
True
Upvotes: 3