gpt4 book ai didi

python 2.6 打印格式 (%) : remove newline

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:40 24 4
gpt4 key购买 nike

我使用 python 2.6 并阅读了许多关于从“打印”中删除新行的链接,但找不到使用模数符号 (%) 进行格式化的用法示例。在我的程序中,我试图在计算数据的循环行中写入,但每行数据来自不同的计算:

while loop    ... calulating value1 and value2    print ('%10d %10s') % (value1, value2)    [1]    ... calulating value3 and value4    print ('%7s %15d') % (value3, value4)    [2]    print #this is where newline should come from

所以我想得到:

value1 value2 value3 value4value5 value6 value7 value8...

基本上这种方法保持了我的程序的可读性(每条实线都有超过 20 个计算位置)。相反的方法是将所有数据连接成一个长字符串,但可能会失去可读性。
是否可以使用 [1] 和 [2] 中的“print () % ()”语法删除换行符?

最佳答案

如果在语句末尾添加逗号(,),换行符将被省略:

print ('%10d %10s') % (value1, value2),

来自 http://docs.python.org/reference/simple_stmts.html#print :

A '\n' character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print.

关于python 2.6 打印格式 (%) : remove newline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11843215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com