代码之家  ›  专栏  ›  技术社区  ›  agftrading

从python 3 for循环打印时,是否可以插入除最后一个分隔符之外的所有分隔符?

  •  1
  • agftrading  · 技术社区  · 7 年前

    请参阅下面的示例,以获得明确的问题:

    此语法:

    print('a','b','c',sep=' @ ')
    

    生成此输出:

    a @ b @ c
    

    这是我想要产生的输出,但是在for循环中。

    到目前为止,我所做的尝试是:

    for item in ['a','b','c']:
        print(item,sep=' @ ')
    

    但这会产生:

    a
    b
    c
    

    还有:

    for item in ['a','b','c']:
        print(item,end=' @ ')
    

    但这会产生:

    a @ b @ c @ 
    

    是否有产生输出的方法:

    A@B@C时
    

    从这个for循环?

    *进一步澄清,因为细节似乎对答案很重要*

    完整设置如下:

    for fruit in df.index.year.unique():
        total = df[df.index.year == year]['Number of Fruits'].sum()
        print(fruit + ' Total: ' + str(total))
    

    我特别想把每个水果和总数打印在同一行上,用“”分隔,但末尾没有出现“”分隔符。

    谢谢!

    3 回复  |  直到 7 年前
        1
  •  2
  •   Olivier Melançon iacob    7 年前

    print

    lst = ['a', 'b', 'c']
    print(*lst, sep=' @ ') # 'a @ b @ c'
    

    lst = []
    
    for fruit in df.index.year.unique():
        total = df[df.index.year == year]['Number of Fruits'].sum()
        lst.append('{} Total: {}'.format(fruit, total))
    
    print(*lst, sep=' @ ')
    
        2
  •  1
  •   Vicrobot    7 年前

    for

    t = ['a','b','c']
    for i in t[:-1]:
        print(i, end=' @ ')
    print(t[-1])
    

    sep

        3
  •  0
  •   letsintegreat israelss    7 年前

    \b print