wheedwhackerjones
wheedwhackerjones

Reputation: 39

How do I print these lines horizontally

I'm trying to print these numbers (in the form of a digital clock) all on the same line. My goal is to have a function take in a few numbers and print them all on the same line.


numbers = {
0: 
[
    
' _ ',
'| |',
'|_|'

],
1: 
[
    
'   ',
'| |',
'| |'
]
}


for k, v in numbers.items():
    for i in range(len(numbers)+1):
        print(v[i])

This will print a number, for example, but the next one is on the next line down.

If I add end="" at the end of the print statement, the number doesn't appear properly. Ty

Upvotes: 0

Views: 107

Answers (4)

mozway
mozway

Reputation: 260600

Use zip!

numbers = {0: [' _ ',
               '| |',
               '|_|'],
           1: ['   ',
               '  |',
               '  |'],
           2: [' _ ',
               ' _|',
               '|_ ']}

target = '0120'

print('\n'.join([' '.join(x) for x in zip(*(numbers[int(x)] for x in target))]))

output:

 _       _   _ 
| |   |  _| | |
|_|   | |_  |_|

Upvotes: 0

mpfmorawski
mpfmorawski

Reputation: 11

I propose a slightly different approach to this task. First create a whole line of text to be printed (consisting of a concatenation of the individual elements of all the numbers), and then print it.

for i in range(3):
    output = ""
    for k, v in numbers.items():
        output += v[i]
    print(output)

Update

To print specific set of numbers using a function you need to iterate through the input variable (not through numbers.items()).

An example function:

def printit(string):
    for i in range(3):
        output = ""
        for num in string:
            output += numbers[int(num)][i]
        print(output)
        
printit('01')

Upvotes: 1

Алексей Р
Алексей Р

Reputation: 7627

numbers = {
    0:
        [
            ' _ ',
            '| |',
            '|_|'
        ],
    1:
        [
            ' /|',
            '  |',
            '  |'
        ],
    2:
        [
            '!--',
            ' / ',
            '|__ '
        ]
}

lines = [''] * 3
for k, v in numbers.items():
    for i in range(len(numbers)):
        lines[i] += v[i] + '   '

for l in lines:
    print(l)

Prints:

 _     /|   !--   
| |     |    /    
|_|     |   |__    

Upvotes: 1

Jonathan F.
Jonathan F.

Reputation: 486

Assuming you are using Python3, you can use

for k, v in numbers.items():
   for i in range(len(numbers)+1):
      print(v[i], end = "")

to print inline. You can additional add a symbol inside the end string to separate items.

Upvotes: 0

Related Questions