-1

I want to wrap the string below:

string = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'

With the max width as 4, for instance I want this output:

Output that I want

I created this function:

def wrap(string, max_width):
    i = max_width
    while True:
        string = string[:i] + '\n' + string[i+1:]
        if i >= len(string):
            break
    return string

if __name__=='__main__':
    string = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'
    print(wrap(string, 4))

But the outputs was:

My Output

May you help me, please?

Isma
  • 14,604
  • 5
  • 37
  • 51
lucas
  • 79
  • 6
  • 2
    Help us help you - paste your code as text, not as a screenshot – Mureinik Dec 31 '19 at 18:23
  • 4
    Consider using the [textwrap](https://docs.python.org/3.9/library/textwrap.html) in the standard library. – snakecharmerb Dec 31 '19 at 18:23
  • Not exact duplicate, but this should help - https://stackoverflow.com/q/312443/2422776 – Mureinik Dec 31 '19 at 18:24
  • 2
    In general when learning to code, you want to master the art of debugging. In this case, where you have a loop, you want to see what is happening in each iteration of the loop. – Arya Dec 31 '19 at 18:27
  • 1
    Please read [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). – martineau Dec 31 '19 at 18:36

4 Answers4

2

The following should work:

def wrap(string, max_width):
    return '\n'.join(string[i:i+max_width] for i in range(0,len(string),max_width))
3ddavies
  • 546
  • 2
  • 19
1

Try this:

string = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'

for i in range(0, len(string), 4):
    print(string[i:i+4])

Output

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
0

Just replace the i+1 with i like this:

string = string[:i] + "\n" + string[i:]
marcos
  • 4,473
  • 1
  • 10
  • 24
0

Another try with regular expression:

def wrap(string, max_width):
    return '\n'.join(re.findall(f'.{{1,{max_width}}}',string))

Philippe
  • 20,025
  • 2
  • 23
  • 32