好的,这很难解释,但我想在句子中添加填充,以便该句子中的字符是 n 的倍数。
但是这个数字“4”必须更改为 3 和 5,所以它也必须工作。
有谁知道我在说什么??怎么做?
我希望下面的自我注释代码可以帮助您掌握这个概念。您只需要做一些数学运算即可在任一端获取填充字符
一些概念
所以这里是代码
>>> def encrypt(st,length):
#Reversed the String and replace all Spaces with 'X'
st = st[::-1].replace(' ','X')
#Find no of characters to be padded.
padlength = (length - len(st)%length) % length
#Pad the Characters at either end
st = 'X'*(padlength/2)+st+'X'*(padlength-padlength/2)
#Split it with size length and then join with a single space
return ' '.join(st[i:i+length] for i in xrange(0,len(st),length))
>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4) #Your Example
'XECN ELIG IVXL ANRE TEXS IXMO DEER FXFO XECI RPXE HTXX'
>>> encrypt('THE PRICE', 5) # One Extra Character at end for Odd Numbers
'ECIRP XEHTX'
>>> encrypt('THE PRIC', 5) # 1 Pad Characters at either end
'XCIRP XEHTX'
>>> encrypt('THE PRI', 5) # 1 Pad Characters at either end and one Extra for being Odd
'XIRPX EHTXX'
>>> encrypt('THE PR', 5) # 2 Pad Characters at either end
'XXRPX EHTXX'
>>> encrypt('THE P', 5) # No Pad characters required
'PXEHT'
>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 5) #Ashwini's Example
'XXECN ELIGI VXLAN RETEX SIXMO DEERF XFOXE CIRPX EHTXX'
>>>
>>> import math
>>> def encrypt(string, length):
inverse_string = string.replace(' ','X')[::-1]
center_width = int(math.ceil(len(inverse_string)/float(length)) * length) # Calculate nearest multiple of length rounded up
inverse_string = inverse_string.center(center_width,'X')
create_blocks = ' '.join(inverse_string[i:i+length] for i in xrange(0,len(inverse_string),length))
return create_blocks
>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4)
'XECN ELIG IVXL ANRE TEXS IXMO DEER FXFO XECI RPXE HTXX'
def pad(yourString,blockLength):
return yourString + ("X" * (blockLength - (len(yourString) % blockLength)))
是你的填充函数。用于结束填充。如果您需要中心填充,请使用:
def centerPad(yourString,blockLength):
return ("X" * ((blockLength - (len(yourString) % blockLength))/2)) + yourString + ("X" * ((blockLength - (len(yourString) % blockLength))/2))
如果要实现块密码,则需要更仔细地查看其余代码。