1

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.

4 Answers 4

3

If it's taken from a file then it's a string.

>>> len('1234567890') == 10
True
Sign up to request clarification or add additional context in comments.

1 Comment

And this also works in the case where leading zeroes are allowed in order to pad to 10 digits - often the case where the "number" is a bank account ID or similar. If 0123456789 is an allowed value, then this works where integer maths does not.
2

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.

1 Comment

I probably would have done this myself but I wonder if it would be overkill to use regular expressions for this particularly if we can do this using a combination of len() and isnumeric().
1

Math - if you need the int anyway:

10**10 <= int('12334567890') < 10**11

Comments

0
if len( str( int( input_variable) ) ) != 10:
     fire_milton(burn_this_place_down=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.