1

I'm trying to insert a newline every 40 characters. I'm very new to Python so I apologize if my code is messed up.

def wrap(msg):
   pos = 0
   end = msg
   for i in end:
       pos += 1
       if pos % 40 == 0:
           print(pos)
           end = end[:pos] + "\n" + end[:pos + 2]

   return end

This code doesn't work and there isn't any errors. I'm not sure why this happens. It seems to just return the full string??

martineau
  • 119,623
  • 25
  • 170
  • 301
Maya
  • 35
  • 3
  • 2
    one other way to do this would be to split the text and join the result : `splitted = "\n".join([msg[i:i+40] for i in range(0, len(msg), 40)])` see [this](https://stackoverflow.com/q/9475241/2614364) – Bertrand Martel Sep 27 '20 at 20:58

1 Answers1

1
def wrap(msg):
    res = ''
    t = len(msg)//40
    for i in range(t):
        start = i*40
        end = (i+1)*40
        res += msg[start:end]+'\n'
    res += msg[t*40:(t+1)*40]
    return res
Khaos101
  • 442
  • 5
  • 14