1

I have a string thestackoverflow and I also have # columns = 4
Then I want the output as

thes  
tack  
over  
flow
Varun Kumar
  • 153
  • 11

2 Answers2

1

You can have a look at textwrap

import textwrap
string = 'thestackoverflow'
max_width = 4
result = textwrap.fill(string,max_width)
print(result)
thes
tack
over
flow

If you don't want to use any module

string = 'thestackoverflow'
max_width = 4
row = 0
result = ''
while row*max_width < len(string):
    result+='\n'+string[row*max_width:(row+1)*max_width]
    row+=1
result = result.strip()
print(result)
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
1

you can do it using python slice notation.
refer to this thread for a nice explanation on slice notation: Understanding slice notation

example code for your question:

>>> input_string = "thestackoverflow"
>>> chop_size = 4
>>> while(input_string):
...  print input_string[:chop_size]
...  input_string = input_string[chop_size:]
...
thes
tack
over
flow