Reputation: 159
I have a question about printing on same line.
I'm trying to do the following:
and the code i wrote is below
dic = {'1':'#\n#\n#\n#\n#',
'2':'###\n #\n###\n#\n###',
'3':'###\n #\n###\n #\n###',
'4':'# #\n# #\n###\n #\n #',
'5':'###\n#\n###\n #\n###',
'6':'###\n#\n###\n# #\n###',
'7':'###\n #\n #\n #\n #',
'8':'###\n# #\n###\n# #\n###',
'9':'###\n# #\n###\n #\n###',
'0':'###\n# #\n# #\n# #\n###'
}
value = input("Enter an integer: ")
value = str(value)
for chr in value:
print(dic[chr], sep=' ')
but with my code when i run it, it prints in separate lines
could you please help how to print on same line.
or if my code is incorrect, could you please advise on how to write it correctly?
thank you in advance!
Upvotes: 0
Views: 321
Reputation: 32954
Your code is incorrect. You need to join the first line of each digit, then the second line, etc.
You can use zip()
to get the lines of the digits together, though to accommodate that, you'll need to transform dic
so that each digit is in separate units for each line, like this:
{k: v.splitlines() for k, v in dic.items()}
You'll also need to fix the spacing so that each unit has a constant width.
Once that's done, get the digits together, zip, and print:
value = input("Enter an integer: ")
digits = [dic[c] for c in value]
for line in zip(*digits):
print(*line)
This uses the unpacking operator (AKA "splat").
BTW, str(input())
is redundant since input()
returns a string.
Upvotes: 0
Reputation: 35512
First write a function combine
that combines two strings into one line, by splitting both strings on a newline, finding the longest section of the first string, then using that to determine the padding:
def combine(a, b):
a_lines = a.split("\n")
b_lines = b.split("\n")
padding = max(len(line) for line in a_lines)
return "\n".join(a_line.ljust(padding) + " " + b_line for a_line, b_line in zip(a_lines, b_lines))
Then, just use it:
dic = {'1':'#\n#\n#\n#\n#',
'2':'###\n #\n###\n#\n###',
'3':'###\n #\n###\n #\n###',
'4':'# #\n# #\n###\n #\n #',
'5':'###\n#\n###\n #\n###',
'6':'###\n#\n###\n# #\n###',
'7':'###\n #\n #\n #\n #',
'8':'###\n# #\n###\n# #\n###',
'9':'###\n# #\n###\n #\n###',
'0':'###\n# #\n# #\n# #\n###'
}
value = input("Enter an integer: ")
value = str(value)
output = ""
for chr in value:
if output:
output = combine(output, dic[chr])
else:
# don't combine with nothing
output = dic[chr]
print(output)
Upvotes: 1