如何在单次print调用中输出f-string等内容且各元素自动换行分隔
解决方案
问题原因
Python内置print()函数默认使用空格作为多个输入参数的分隔符,因此你传入的所有内容会被空格拼接后输出。
方法1:直接指定分隔符为换行符
最简单的实现方式是给print()添加sep='\n'参数,指定多个内容之间用换行符分隔:
print( f'Revenue as stated in the General Journal is ${a}', f'Revenue as stated in the Transaction Table is ${b}', f'Revenue is overstated by ${c}', rt.info(), rtrtl.info(), rt.head(10), rtrtl.head(10), sep='\n' )
注意:pandas对象的
info()方法本身会直接向控制台输出内容,返回值为None,如果直接放在print()参数中,会在对应位置额外打印None。
方法2:统一捕获pandas输出后打印(无多余None)
如果你需要把info()的输出也和其他内容统一按行打印,可以先捕获info()的输出内容再传入print():
import io # 捕获rt.info的输出 rt_buf = io.StringIO() rt.info(buf=rt_buf) rt_info_str = rt_buf.getvalue() # 捕获rtrtl.info的输出 rtrtl_buf = io.StringIO() rtrtl.info(buf=rtrtl_buf) rtrtl_info_str = rtrtl_buf.getvalue() print( f'Revenue as stated in the General Journal is ${a}', f'Revenue as stated in the Transaction Table is ${b}', f'Revenue is overstated by ${c}', rt_info_str, rtrtl_info_str, rt.head(10), rtrtl.head(10), sep='\n' )
内容的提问来源于stack exchange,提问作者Johnnyduke
相关产品推荐
相关产品推荐

