Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

python - How to retain leading zeros of int variables?

Below is a section of code which is part of a functional decryption and encryption program.

while checkvar < maxvar: # is set to < as maxvar is 1 to high for the index of var
    #output.append("%02d" % number)
    i =ord(var[checkvar]) - 64 # Gets postional value of i
    i = ("%02d" % i)
    if (checkvar + 1) < maxvar:
        j =ord(var[(checkvar + 1)]) - 64 # Gets postional value of i
        j = ("%02d" % j)
        i = str(i) + str(j) #'Adds' the string i and j to create a new i
    li.append(int(i))
    checkvar = checkvar + 2

print li

As you can see the two variables i and j are first treated as string to add a 0 in front of any single digit numbers (as string). These variables then are combined to make a four digit number (still as a string). Later in the program the number created are used in a pow() function, as ints remove any leading zeros.

My question: Is it possible to force python to keep the leading zero for ints? I have and continued to search online.

Edit

To help people I have included the encryption part of the program. This is where the problem lies. The variables created in the above code are passed through a pow() function. As this can't handle strings I have to convert the variables to ints where the leading zero is lost.

#a = li[]
b=int(17)#pulic = e
c=int(2773)#=n

lenli=int(len(li))
enchecker = int(0)

#encrpted list
enlist = []

while enchecker < lenli:
    en = pow(li[enchecker],b,c)#encrpyt the message can only handle int
    enlist.append(int(en))
    enchecker = enchecker + 1

print enlist
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Though the comments above are true regarding 1, 01, and 001, are all the same as an int, it can be very helpful in temporal modeling, or sequential movie making to maintain the leading zeros. I do it often to ensure movie clips are in proper order. The easy way to do that is using zfill() to ensure the str version of the number has at least the number of characters you tell it, and does so by filling in the left-side of the string "number" with zeros.

>>> x = int(1)    
>>> NewStringVariable = str(x).zfill(3)    
>>> print NewStringVariable    
001    
>>> NewStringVariable = str(x).zfill(5)    
>>> print NewStringVariable    
00001

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...