Print in one line dynamically

后端 未结 20 3249
梦谈多话
梦谈多话 2020-11-21 23:32

I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for it         


        
20条回答
  •  情话喂你
    2020-11-22 00:02

    In Python 3 you can do it this way:

    for item in range(1,10):
        print(item, end =" ")
    

    Outputs:

    1 2 3 4 5 6 7 8 9 
    

    Tuple: You can do the same thing with a tuple:

    tup = (1,2,3,4,5)
    
    for n in tup:
        print(n, end = " - ")
    

    Outputs:

    1 - 2 - 3 - 4 - 5 - 
    

    Another example:

    list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
    for item in list_of_tuples:
        print(item)
    

    Outputs:

    (1, 2)
    ('A', 'B')
    (3, 4)
    ('Cat', 'Dog')
    

    You can even unpack your tuple like this:

    list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
    
    # Tuple unpacking so that you can deal with elements inside of the tuple individually
    for (item1, item2) in list_of_tuples:
        print(item1, item2)   
    

    Outputs:

    1 2
    A B
    3 4
    Cat Dog
    

    another variation:

    list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
    for (item1, item2) in list_of_tuples:
        print(item1)
        print(item2)
        print('\n')
    

    Outputs:

    1
    2
    
    
    A
    B
    
    
    3
    4
    
    
    Cat
    Dog
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题