如何在Python中打印空行?
我一直找不到相关的信息。
我想知道怎么使用一个函数(比如 clear_screen
),这个函数可以打印出20行空白。
我程序的最后一行应该是调用 clear_screen
。
我的代码开头是:
def new_line():
print
def three_lines():
new_line()
new_line()
new_line()
def nine_lines():
three_lines()
three_lines()
three_lines()
print " "
nine_lines()
print " "
打印功能是可以用的,但 clear_screen()
这个却不行,这正是我需要的功能。
如果有人能帮我或者有任何建议,那就太好了,谢谢。
2 个回答
3
你的 clear_screen
可以有以下几种实现方式:
基于
os.system
的方法def clear_screen(): import os os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
这种方法在 Unix 和 Windows 系统上都能用。
来源: 这里基于换行符的方法
def clear_screen(): print '\n'*19 # print creates it's own newline
根据你的评论,看起来你的代码是
def new_line():
print
def three_lines():
new_line()
new_line()
new_line()
def nine_lines():
three_lines()
three_lines()
three_lines()
print " "
nine_lines()
print " "
这个方法可以工作,而且确实有效,
但是 如果 print '\n'*8
也能做到同样的事情,为什么要写这么长的代码呢?
速度测试
即使你没有速度限制,这里有一些关于每种方法运行100次的速度统计数据
os.system function took 2.49699997902 seconds.
'\n' function took 0.0160000324249 seconds.
Your function took 0.0929999351501 seconds.
3
我觉得没有一种通用的方法可以在不同平台上都适用。所以,不要依赖于 os.*
,可以试试下面的方法。
print("\n"*20)