有没有一种方法可以只使用一个打印语句,但仍能达到与下面代码相同的效果?我尝试了结束语句,但在这种情况下其中一个不起作用,或者我使用不正确:
print ('Deposit: ' + str(deposit))
print ('Withdrawl: ' + str(withdrawl))
print ('Available amount: ' + str((deposit + withdrawl)//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
调用的需要,并且更具可读性(它可以做更多的事情,请参阅链接)。
I have attempted end statements to which either one dont work in this situation or, I am using incorrectly
我假设你使用了像 print('foo', 'bar', end='\n')
这样的东西,这不会起作用,因为 end
是仅附加到所有参数的结尾 end ; sep
参数在参数之间打印(默认为空格)。
所以你想要做的是:print('foo', 'bar', sep='\n')
这样做的缺点是,您将需要 3 个 .format
调用,或者保持“丑陋”的字符串连接。
关于python - 如何使用一个打印语句但仍打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784505/