Home > database >  How to wrap from the other end with textwrap?
How to wrap from the other end with textwrap?

Time:11-09

wrap in textwrap wraps from left to right:

from textwrap import wrap
print(wrap('1100010101', 4))

returns: ['1100', '0101', '01']

Is there a way to wrap it from right to left, so it returns: ['11', '0001', '0101']?

CodePudding user response:

You can first reverse '1100010101' then reverse each element and at end reverse result of wrap like below:

>>> from textwrap import wrap
>>> st = '1100010101'[::-1]
>>> list(map(lambda x: x[::-1] , wrap(st, 4)))[::-1]
['11', '0001', '0101']

CodePudding user response:

Couldn't find anything on the docs. Maybe you can create your own function:

def wrap(t, c):
    a = len(t) % c
    output = []
    if a:
        output = [t[:a]]
    for i in range(len(t) // c):
        output.append(t[a   i*c: a   (i 1)*c])
    return output
  • Related