Reputation: 153
I have a string thestackoverflow
and I also have # columns = 4
Then I want the output as
thes
tack
over
flow
Upvotes: 1
Views: 104
Reputation: 3856
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)
Upvotes: 1
Reputation: 73
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
Upvotes: 1