简体   繁体   English

如何在带空格和不带换行的 python 循环中打印

[英]how print in python loop with space and without new line

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:您可以使用“\\n”创建一个新行,如下所示:

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:for循环中只有 1 行代码而不是额外条件的另一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM