Varun Kumar
Varun Kumar

Reputation: 153

I want to print the letters in each word in matrix form given the number of columns

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

Answers (2)

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

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

user12386945
user12386945

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

Related Questions