Vertical Print String - Python3.2
Asked Answered
S

3

6

I'm writing a script that will take as user inputed string, and print it vertically, like so:

input = "John walked to the store"

output = J w t t s
         o a o h t
         h l   e o
         n k     r
           e     e
           d

I've written most of the code, which is as follows:

import sys

def verticalPrint(astring):
    wordList = astring.split(" ")
    wordAmount = len(wordList)

    maxLen = 0
    for i in range (wordAmount):
        length = len(wordList[i])
        if length >= maxLen:
            maxLen = length

    ### makes all words the same length to avoid range errors ###
    for i in range (wordAmount):
        if len(wordList[i]) < maxLen:
            wordList[i] = wordList[i] + (" ")*(maxLen-len(wordList[i]))

    for i in range (wordAmount):
        for j in range (maxLen):
            print(wordList[i][j])

def main():
    astring = input("Enter a string:" + '\n')

    verticalPrint(astring)

main()

I'm having trouble figure out how to get the output correct. I know its a problem with the for loop. It's output is:

input = "John walked"

output = J
         o
         h
         n

         w
         a
         l
         k
         e
         d

Any advice? (Also, I want to have the print command used only once.)

Signification answered 27/10, 2013 at 19:4 Comment(0)
H
12

Use itertools.zip_longest:

>>> from itertools import zip_longest
>>> text = "John walked to the store"
for x in zip_longest(*text.split(), fillvalue=' '):
    print (' '.join(x))
...     
J w t t s
o a o h t
h l   e o
n k     r
  e     e
  d      
Hydrant answered 27/10, 2013 at 19:7 Comment(1)
Very nice. Or izip_longest on python 2.xRoping
S
0

Thanks so much for the help! That definitely worked!

I ended up speaking to a friend of mine not long after posting this, and I modified the for loops to the following:

newline = ""

    for i in range (maxLen):
        for j in range (wordAmount):
            newline = newline + wordList[j][i]
        print (newline)
        newline = ""

which worked beautifully as well.

Signification answered 27/10, 2013 at 19:21 Comment(0)
A
-2
a = input()
for x in range (0,len(a)):
    print(a[x])
Arondell answered 9/12, 2020 at 11:29 Comment(1)
This does not solve the OP's problem, this will only print all letters in new lines, your indentation is messed and you did not add any explanation to your code, try to edit your answer or consider removing it, as it is incorrect.Soffit

© 2022 - 2024 — McMap. All rights reserved.