I want space between every number and a new line between two different numbers.
My code:
num = [4 , 2]
for item in num:
for i in range(item):
print(item ,end="")
Desired output:
4 4 4 4
2 2
Current output:
444422
CodePudding user response:
Try this:
num = [4 , 2]
for item in num:
for i in range(item):
print(item, end=" ")
print()
Edit:
I think it's overcomplicated for a problem like this, but you can try (it shouldn't print extra space at the end):
num = [4 , 2]
for item in num:
for i in range(item):
if item - 1 == i:
print(item)
else:
print(item, end=" ")
It prints an item with a new line when it's the last number in the second loop otherwise it prints the number with a space.
CodePudding user response:
You can use "\n" which creates a new line as follow:
num = [4 , 2]
for item in num:
for i in range(item):
print(item, end=" ")
print("\n")
Make sure the end has space in it; like " " instead of ""
CodePudding user response:
num = [4 , 2]
for item in num:
x = (str(item) " ") * item
x = x.rstrip()
print(x,end="")
print()
CodePudding user response:
Another approach with just 1 line of code inside for
loop and not extra conditions:
num = [4 , 2]
for item in num:
# [str(item)]*item creates a list with 'item' repeated 'item' no. of time.
# Join this list with a space
print (" ".join([str(item)]*item))
Output:
4 4 4 4
2 2