如何在字符串中添加字符填充? [英] How do I add character padding to a string?
本文介绍了如何在字符串中添加字符填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,这很难解释,但是我想在句子中添加填充,以使该句子中的字符为n的倍数.
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.
但是这个数字"4"必须更改为3和5,因此它也必须工作..
however this number '4' has to change to 3 and 5 so it has to work then as well..
有人知道我在说什么吗?以及如何做?
anyone know what im talking about?? and how to do it?
推荐答案
我希望下面的自我注释代码可以帮助您理解这一概念.您只需要做一些数学运算即可获得两端的填充字符
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
一些概念
- 需要的额外字符填充= len(string)%block_length
- Total_Pad_Characters = block_length-len(string)%block_length
- 前面的填充字符= Total_Pad_Characters/2
- 结尾处的填充字符= Total_Pad_Characters-Total_Pad_Characters/2
这是代码
>>> 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'
>>>
这篇关于如何在字符串中添加字符填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文