i do not want new line in same output and want space between every two numbers the code :
num = [4 , 2]
for item in num:
for i in range(item):
print(item ,end="")
what I want :
4 4 4 4
2 2
what I get :
444422
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.
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 ""
num = [4 , 2]
for item in num:
x = (str(item)+" ") * item
x = x.rstrip()
print(x,end="")
print()
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.