0

I need to take a variable-length string and make it a fixed-length for struct.pack().

if the input string is:

  • longer than size, then it needs to be truncated
  • shorter than size, then it needs to be padded

there doesn't seem to be a one-line method for padding or truncating a string to a fixed length

what's simpler than this?

in_str='abcd1234'
size=12 # or 4
def make_str_this_len(in_str,size):
    if size<=len(in_str):
        out_str = in_str[0:size]
    else:
        out_str = in_str.ljust(size)
    return out_str

# printing string and its length
res=make_str_this_len(in_str,size)
print("resulting string:[{0}], len={1}".format(res,len(res)))

1 Answer 1

1

How about this?

def make_str_this_len(in_str,size):
    return in_str.ljust(size)[0:size]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.