Printing words vertically in Python

| | | | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

The given string s. Return all words vertically in the same order as they appear in s.
Words are returned as a string list, padded with spaces when necessary. (Walking on the steps is not allowed).
Each word will only be placed in one column and there will be only one word per column.

Printing words vertically in Python

Example 1:

Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically. 
 "HAY"
 "ORO"
 "WEU"

Example 2:

Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed. 
"TBONTB"
"OEROOE"
"   T"

Example 3:

Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]

Constraints:

  • 1 <= s.length <= 200
  • s contains only upper case English letters.
  • It’s guaranteed that there is only one space between 2 words.

Method #1 : [Horizontal to Vertical] using loop + ""

In this, we add newline character to after each character so that each element gets rendered at next line.

# Python3 code to demonstrate working of
# Interconvert Horizontal and Vertical String
# using [Horizontal to Vertical] using loop + "
"

# initializing string
test_str = ’geeksforgeeks’

# printing original String
print("The original string is : " + str(test_str))

# using loop to add "
" after each character
res = ’’
for ele in test_str:
	res += ele + "
"
	
# printing result
print("The converted string : " + str(res))

Output:

Output
The original string is : geeksforgeeks
The converted string : g
e
e
k
s
f
o
r
g
e
e
k
s

Method #2 : [Vertical to Horizontal] using replace() + ""

In this, we perform the task of conversion by removing "
" by replacement by empty string.

# Python3 code to demonstrate working of 
# Interconvert Horizontal and Vertical String
# using [Vertical to Horizontal] using replace() + "
"
  
# initializing string
test_str = ’g
e
e
k
s
f
o
r
g
e
e
k
s
’
  
# printing original String
print("The original string is : " + str(test_str))
  
# using replace() + "
" to solve this problem
res = test_str.replace("
", "")
      
# printing result 
print("The converted string : " + str(res)) 

Output:

The original string is : g
e
e
k
s
f
o
r
g
e
e
k
s

The converted string : geeksforgeeks
Printing words vertically in Python

Vertical Print String - Python3.2

StackOverflow question

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:" + ’
’)

    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.)

Answer:

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      

Suppose we have string s. We have to find all the words vertically in the same order in which they appear in s. Here the words are returned as a list of strings, if necessary, we have to fill in spaces. (Trailing spaces are not allowed.) Each word will be placed in only one column, and there will be only one word in one column. Thus, if the input string is "LIKE YOU?", Then the output will be ["HAY", "ORO", "WEU"]

To solve this problem, we will follow the following steps:

  • s := make a list of strings split by the spaces, make one empty array x, set row = 0
  • for each word I in s, set row := max of row and length of i
  • col := length of s
  • make one array and filled with empty string, and its size is the row
  • for I in range 0 to col ‚Äì 1
  • j := 0
  • while j < length of s[i]
    • while i < length of ans[j] >= 1, do ans[j] := ans[j] concatenate " ‚"
    • ans[j] := ans[j] concatenate s[i, j]
    • increase j by 1
  • return ans
class Solution(object):
   def printVertically(self, s):
      s = s.split(" ")
      x = []
      row = 0
      for i in s:
         row = max(row, len(i))
      col = len(s)
      ans = ["" for i in range(row)]
      j = 0
      for i in range(col):
         j = 0
         while j < len(s[i]):
            #print(j, i)
            while i - len(ans[j]) >= 1:
               ans[j] += " "
            ans[j] += s[i][j]
            j += 1
      return ans
ob = Solution()
print(ob.printVertically("HOW ARE YOU"))
print(ob.printVertically("TO BE OR NOT TO BE"))

Input:

"HOW ARE YOU"
"TO BE OR NOT TO BE"

Output:

["HAY","ORO","WEU"]
["TBONTB","OEROOE"," T"]
Printing words vertically in Python

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Printing words vertically in Python, check other __main__ Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Oliver Richtgofen

Milan | 2023-01-27

Simply put and clear. Thank you for sharing. Printing words vertically in Python and other issues with join was always my weak point 😁. Checked yesterday, it works!

Manuel Jackson

Paris | 2023-01-27

Thanks for explaining! I was stuck with Printing words vertically in Python for some hours, finally got it done 🤗. I am just not quite sure it is the best method

Walter Schteiner

Berlin | 2023-01-27

Simply put and clear. Thank you for sharing. Printing words vertically in Python and other issues with Zip PHP module was always my weak point 😁. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically