如何在字符串中添加字符填充?

时间:2012-04-09 08:45:14

标签: python string padding

好的,这很难解释,但我想在句子中添加填充,以便该句子中的字符是n的倍数。

然而,这个数字'4'必须改为3和5,所以它也必须工作..

任何人都知道我在说什么?以及如何做到这一点?

3 个答案:

答案 0 :(得分:2)

我希望下面的自评论代码可以帮助您掌握这个概念。你只需要做一些数学运算来获得两端的填充字符

一些概念

  1. 需要额外字符填充= len(字符串)%block_length
  2. Total_Pad_Characters = block_length - len(string)%block_length
  3. 前面的Pad字符= Total_Pad_Characters / 2
  4. Pad字符末尾= Total_Pad_Characters - Total_Pad_Characters / 2
  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'
    >>>
    

答案 1 :(得分:0)

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))
如果你想实现一个块密码,你需要更加努力地查看其余的代码。

答案 2 :(得分:0)

>>> 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'