Home > OS >  How to print the elements of a tuple sided by side
How to print the elements of a tuple sided by side

Time:02-07

I am able to print the elements one after the another but I want the result to be printed side by side: 1234, instead of:
1
2
3
4
Display which I am getting
enter image description here
Desired Output:
enter image description here

The code is to display 7 segment led display.

led_dict={
    '0':('###','# #','# #','# #','###'),
    '1':('  #','  #','  #','  #','  #'),
    '2':('###','  #','###','#  ','###'),
    '3':('###','  #','###','  #','###'),
    '4':('# #','# #','###','  #','  #'),
    '5':('###','#  ','###','  #','###'),
    '6':('###','#  ','###','# #','###'),
    '7':('###','  #','  #','  #','  #'),
    '8':('###','# #','###','# #','###'),
    '9':('###','# #','###','  #','###')
    }

x = input('Enter a number to be displayed: ')

d_list=[]

for num in str(x):
    d_list.append(led_dict[num])
print(d_list)
# for i in range(5):
#     for ab in d_list:
#         print(ab[i])

for ab in d_list:
    for i in range(5):
        print((ab[i]))

CodePudding user response:

Try this:

for i in range(5):
    print(' '.join(k[i] for k in d_list))

How it works;

Each number tuple consists of five lines. But we have to print by line. That means we have to join the same elements of the tuple for all digits, and then print the resulting string. If we do that five times, (see the index i) we will have printed the whole number.

An example:

Python 3.9.9 (main, Dec 11 2021, 14:34:11) 
>>> led_dict={'0': ('###', '# #', '# #', '# #', '###'),
...  '1': ('  #', '  #', '  #', '  #', '  #'),
...  '2': ('###', '  #', '###', '#  ', '###'),
...  '3': ('###', '  #', '###', '  #', '###'),
...  '4': ('# #', '# #', '###', '  #', '  #'),
...  '5': ('###', '#  ', '###', '  #', '###'),
...  '6': ('###', '#  ', '###', '# #', '###'),
...  '7': ('###', '  #', '  #', '  #', '  #'),
...  '8': ('###', '# #', '###', '# #', '###'),
...  '9': ('###', '# #', '###', '  #', '###')}
>>> d_list=[]
>>> for num in '3427':
...     d_list.append(led_dict[num])
... 
>>> for i in range(5):
...     print(' '.join(k[i] for k in d_list))
... 
### # # ### ###
  # # #   #   #
### ### ###   #
  #   # #     #
###   # ###   #

  •  Tags:  
  • Related