Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python integer prefix range algorithm

Here is my problem. I have various integer inputs varying in length, but I only want certain number prefixes to be printed. The prefix ranges are 20000-20150 all five digits. So far I have:

print 20000 <= prefix <= 20150

which is fine, but how do I find or capture the prefix '20000' in the number using Python.

example:20000201501

using the code below won't work, in such cases because there are two instances where the value of prefix is present, I only want the first prefix.

obj = 20000201501
if prefix in obj
    print prefix 
like image 212
Rayshawn Avatar asked Jun 12 '26 17:06

Rayshawn


2 Answers

Very simply:

>>> num = 20000201501
>>> print int(str(num)[:5])
20000

So, you need something like this:

def prefix(num):
    return int(str(num)[:5])

print 20000 < prefix(20000201501) < 20150
like image 72
defuz Avatar answered Jun 14 '26 07:06

defuz


You can make the object a string (using str), slice the first 5 characters off of it (as the prefix) and then convert that back to an integer (using int):

 prefix = int(str(obj)[:5])
like image 29
mgilson Avatar answered Jun 14 '26 09:06

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!