如何在python中以类似于setLength属性java的方式为字符串设置固定长度



我在python中有一个场景,我需要确保变量设置为特定的长度。 它不能超过或低于 x 个字符。如果变量较小,我需要在行尾附加 \u0000 个空格(类似于 java 执行任务的方式(。

Java在他们的StringBuffer类中有一个名为setLength的属性,它允许为变量设置固定长度。 我创建了一个函数供我使用,但想使用标准 python 库来执行此操作。

python中是否有类似的功能?

'''
' The setLength function will set the length of a string.  
' This is similar to the setLength attribute in java
' The end of the string should be padded with u0000
'''
def setLength(sVal,length=0):
sLength = len(sVal)
if sLength > length:
sVal = sVal[:length-sLength]
elif sLength < length:
thePadding = length - sLength
theBuffer = "".join(['u0000' for x in range(thePadding)])
sVal = sVal+theBuffer
return sVal
exampleA=setLength('I love it dude!',15)
print(exampleA)
exampleB=setLength('I love it!',15)
print(exampleB)
exampleC=setLength('I love it dude! How can we add more to this string?',15)
print(exampleC)

你可以很容易地写一个:

padding_char = '*'
def setLength(s, max_length):
return (s + padding_char * max_length) [:max_length]
exampleA=setLength('I love it dude!',15)
print(exampleA)
exampleB=setLength('I love it!',15)
print(exampleB)
exampleC=setLength('I love it dude! How can we add more to this string?',15)
print(exampleC)

指纹:

I love it dude!
I love it!*****
I love it dude!

使用 str.format(( 可能是一个选项:

'{0:u0000<15.15}'.format('I love it dude!')

其中u0000是要填充到最小长度的字符,<是文本的对齐方式(在本例中为左侧(,第一个15最小长度,第二个15最大长度。

您可以使用ljust来填充额外的字符。

def setLength(s, width):
if len(s) < width:
return s.ljust(width - len(s), 'u0000')
else:
return s[:width]

最新更新