【问题标题】:How to use one print statement yet still print on multiple lines如何使用一个打印语句但仍打印多行
【发布时间】:2014-11-06 16:31:17
【问题描述】:

有没有一种方法可以只使用一个打印语句,但仍能达到与下面代码相同的效果?我尝试了 end 语句,但在这种情况下其中一个不起作用,或者我使用不正确:

print ('Deposit: ' + str(deposit))
print ('Withdrawl: ' +  str(withdrawl))
print ('Available amount: ' + str((deposit + withdrawl)//1))

【问题讨论】:

    标签: python string output


    【解决方案1】:

    是的,您可以使用\n 插入换行符:

    print('Deposit: {}\nWithdrawl: {}\nAvailable amount: {}'.format(
        deposit, withdrawl, (deposit + withdrawl) // 1))
    

    但这并不一定更好。恕我直言,在这里使用单独的 print() 语句更具可读性。

    你可以用字符串连接让它稍微好一点:

    print(('Deposit: {}\n' +
        'Withdrawl: {}\n' +
        'Available amount: {}').format(deposit, withdrawl, (deposit + withdrawl) // 1)
    

    同样,恕我直言,这不一定更好。

    我还使用了format 来提高可读性;这消除了手动调用str 的需要,并且更具可读性(它可以做更多事情,请参阅链接)。

    我尝试了 end 语句,但要么在这种情况下不起作用,要么我使用不正确

    我假设你使用了print('foo', 'bar', end='\n') 之类的东西,这是行不通的,因为end 只附加到所有参数的末尾endsep 参数在参数之间打印(默认为空格)。
    所以你要做的是:print('foo', 'bar', sep='\n')

    这样做的缺点是您将需要 3 次 .format 调用,或者保留“丑陋”的字符串连接。

    【讨论】:

      【解决方案2】:

      看起来您使用的是 Python 3.x。如果是这样,那么您可以将printsep parameter 设置为'\n',以便让每个参数用换行符分隔:

      print('Deposit: ' + str(deposit), 'Withdrawl: ' +  str(withdrawl), 'Available amount: ' + str((deposit + withdrawl)//1), sep='\n')
      

      虽然这确实会让你排很长的队。您可能需要考虑将其拆分为两行:

      print('Deposit: ' + str(deposit), 'Withdrawl: ' +  str(withdrawl),
            'Available amount: ' + str((deposit + withdrawl)//1), sep='\n')
      

      请注意,您也可以在选定的位置放置几个换行符。这将使您可以简单地编写上述内容:

      print('Deposit: ', deposit, '\nWithdrawl: ', withdrawl, '\nAvailable amount: ', (deposit + withdrawl)//1)
      

      这个解决方案的好处是它摆脱了所有对str 的调用(print 自动将其参数字符串化)。


      最后但同样重要的是,如果您实际使用的是 Python 2.x,那么您可以从 __future__ 导入 Python 3.x print 函数。将此行放在代码的顶部:

      from __future__ import print_function
      

      【讨论】:

        【解决方案3】:

        你可以像这样使用模板渲染:

        template = '''Deposit: {0}
        Withdrawal: {1}
        Available amount: {2}'''
        
        deposit = 1000
        withdrawal = 900
        
        print template.format(deposit, withdrawal, (deposit + withdrawal)//1)
        

        但是我没有得到平衡公式,你能解释一下吗?

        【讨论】:

          【解决方案4】:

          或者你可以使用这个

           print(('Deposit: %s\n' +
                'Withdrawl: %s\n' +
                'Available amount: %s') % (deposit, withdrawl, (deposit + withdrawl) // 1)
          

          【讨论】:

            最近更新 更多