How Do I Add Character Padding To A String?
Okay this is very hard to explain, but i want to add padding to a sentence so that the characters in that sentence are a multiple of n. however this number '4' has to change to 3 a
Solution 1:
I hope the self commented code below would help you grasp the concept. You just have to do some maths to get the pad characters at either end
Some concept
- Extra Characters required Padding = len(string) % block_length
- Total_Pad_Characters = block_length - len(string) % block_length
- Pad Character's at front = Total_Pad_Characters/2
- Pad Character's at end = Total_Pad_Characters - Total_Pad_Characters/2
So here is the code
>>> defencrypt(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 spacereturn' '.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'
>>>
Solution 2:
>>> import math
>>> defencrypt(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'
Solution 3:
defpad(yourString,blockLength):
return yourString + ("X" * (blockLength - (len(yourString) % blockLength)))
Is your padding function. for end padding. If you need center padding use:
defcenterPad(yourString,blockLength):
return ("X" * ((blockLength - (len(yourString) % blockLength))/2)) + yourString + ("X" * ((blockLength - (len(yourString) % blockLength))/2))
you need to take a harder look at the rest of your code if you want to implement a block cypher.
Post a Comment for "How Do I Add Character Padding To A String?"