Home > Back-end >  how to use modulo (%) to wrap characters
how to use modulo (%) to wrap characters

Time:01-21

im trying to use mod in python but something is going wrong

my code:


def wrap(string, max_width):
    result = ''
    for i in range(len(string)):
        result  = string[i]
        if i % max_width-1 == 0:
            result  = '\n'
    
    return result

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

my input:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
4

my output:

AB
CDEF
GHIJ
KLMN
OPQR
STUV
WXYZ

but my expected output is:

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

I couldn't find whats wrong, the debugger seems to give wrong results ty

CodePudding user response:

Your data looks like this for a wrap of 4:

letter      A  B  C  D  E  F  G  H  I  J   K   L   M   N   O ...
index       0  1  2  3  4  5  6  7  8  9  10  11  12  13  14 ...
modulo      0  1  2  3  0  1  2  3  0  1   2   3   0   1   2 ...
mod(idx 1)  1  2  3  0  1  2  3  0  1  2   3   0   1   2   3 ...

So, you want to wrap when the modulo equals max_width-1 (here 3), or maybe easier to get, when modulo(index 1) equals 0:

def wrap(string, max_width):
    result = ''
    for i in range(len(string)):
        result  = string[i]
        if (i 1) % max_width == 0:
            result  = '\n'
    
    return result

print(wrap('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4))

output:

ABCD
EFGH
IJKL
MNOP
QRST
UVWX
YZ

CodePudding user response:

You can use enumerate to get characters along with their position. You cna also tell it to start at 1 which will make the modulo operation work on the appropriate breaking indexes:

def wrap(string, max_width):
    result = ''
    for i,c in enumerate(string,1):
        result  = c
        if i % max_width == 0:
            result  = '\n'        
    return result

alternatively, you could use a striding subscript to break down the string into chunks and assemble them using join:

def wrap(string, width):
    return "\n".join(string[i:i width] for i in range(0,len(string),width))

or combine the logic into a single comprehension fed to the join funciton:

def wrap(string, width):
    return "".join(c "\n"[i%width:] for i,c in enumerate(string,1))
  •  Tags:  
  • Related