Home > database >  Printing multiple objects on the same line
Printing multiple objects on the same line

Time:09-03

I was wondering if anyone could help me create a star pattern of letters. I want to see to have either UP or DOWN on the same line. At the moment, however, the letters are printed underneath each other rather than next on the same line. Any help would be greatly appreciated thank you.

Sample the U function:

def u():
    u_str = ''
    for row in range (0,7):
        for column in range (0,7):
            if (((column == 1 or column==5) and row !=6) or ((column==2 or column ==3 
               or column==4) and row==6)) :
               u_str  = "*"
            else:
                u_str  = " "
         u_str  = "\n"
     return u_str

function for entering either up or down

def up_or_down():
    if len(user_letters) ==4 and user_letters == "DOWN":
        print(d() o() w() n())
    elif len(user_letters) ==2 and user_letters == "UP":
        print(u() p())
    else:
        pass

up_or_down()

CodePudding user response:

First, I suggest that you use a dict to store letters ascii art, so you are not recomputing them multiple times:

ascii_letters = {
    "D": d(),
    "N": n(),
    "O": o(),
    "P": p(),
    "U": u(),
    "W": w(),
}

Then create a function that can horizontally concatenate multilines strings:

def hcat_strings(*strings):
    """`strings` must have the same number of lines"""
    # in a single line
    # return "\n".join(("  ".join(l) for l in zip(*(s.splitlines() for s in strings))))
    strings_lines = (s.splitlines() for s in strings)
    lines_as_tuples = zip(*strings_lines)
    lines = ("  ".join(l) for l in lines_as_tuples)
    return "\n".join(lines)

Which you can finally use as follows:

from operator import itemgetter

text = "UPPUPU"
letters = itemgetter(*text)(ascii_letters)

print(hcat_strings(*letters))

Result:

*   *  *****  *****  *   *  *****  *   *
*   *  *   *  *   *  *   *  *   *  *   *
*   *  *   *  *   *  *   *  *   *  *   *
*   *  *****  *****  *   *  *****  *   *
*   *  *      *      *   *  *      *   *
*   *  *      *      *   *  *      *   *
 ***   *      *       ***   *       ***
  • Related