structure opened this issue on Jun 27, 2019 ยท 94 posts
adp001 posted Tue, 09 November 2021 at 6:11 AM
Function to trim/extend array, tuple, bytes or string to a fixed number of elements:
def trimmed(arg, nr_of_elements, f=None):
return (arg + arg.__class__([f, ] * nr_of_elements)
if isinstance(arg, (tuple, list))
else (arg + arg.__class__((f or " ") * nr_of_elements)
if isinstance(arg, (str, bytes))
else [arg, ] + [f, ] * nr_of_elements))[:nr_of_elements]
("f" is what is used to fill missed elements; should be compatible with 'arg')
trimmed([1,2,3], 5) # returns list: [1, 2, 3, None, None]
trimmed((1,2,3), 5) # returns tuple: (1, 2, 3, None, None)
trimmed([1, 2, 3, 4, 5, 6, 7, 8, 9], 5) # returns list: [1, 2, 3, 4, 5]
trimmed("Sample", 10, ".") # returns string: "Sample...."
trimmed(b'123', 5, b'.') # returns bytes: b'123..'
trimmed(10, 5, 1) # returns [10, 1, 1, 1, 1]
trimmed(10, 5, [1, 2, 3]) # returns [10, [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
trimmed([], 5, 1) # returns list: [1, 1, 1, 1, 1]
trimmed((), 5, 1) # returns tuple: (1, 1, 1, 1, 1)