python - 如何使用一个打印语句但仍打印多行

标签 python string output

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

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 是仅附加到所有参数的结尾 endsep 参数在参数之间打印(默认为空格)。
所以你想要做的是:print('foo', 'bar', sep='\n')

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

关于python - 如何使用一个打印语句但仍打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784505/

相关文章:

python - 更改 SparseDataFrame 中的 fill_values - 替换抛出 TypeError

python - Twisted PerspectiveBroker callRemote from wsgi webapp

python - 我想抓取多个页面,但我得到了最后一个 url 的结果。为什么?

javascript - 如何使用JavaScript将文本中的URL提取到数组中

c - 使用系统调用和打印行读取文件

c - 为什么 scanf() 接受错误的输入?

java - JOptionPane 输出文本副本

python - 如何获取 SQLALchemy 查询中实体的类型

java - 以下样本的正确 map 格式是什么?

Java String.startsWith() "seems"不适用于文本文件的第一行