开发者

python number length validator

I am trying to write a python script that validates if an input n开发者_如何学编程umber 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.


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

>>> len('1234567890') == 10
True


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.


Math - if you need the int anyway:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜