python print汇总

  1. print
# 打印进度
for i in range(30):
    print('
%d'%i, end='', flush=True)
    time.sleep(1)

# 机器学习打印环境
def update_env(L):
    while True:
        env_list = ['T']+ ['-'] * int(L) + ['T']
        S = random.randint(1, L)
        env_list[S] = 'o'
        interaction = ''.join(env_list)
        print('
{}'.format(interaction), end='')
        time.sleep(0.3)

update_env(10)


# print与sys.stdout
这里的sys.stdout也就是我们python中标准输出流,这个标准输出流默认是映射到打开脚本的窗口的,
所以,我们的print操作会把字符打印到屏幕上。

import sys
sys.stdout.write(str(123)+'
')
# 等价于:
print 123


import sys
temp = sys.stdout
sys.stdout = open('test.txt','w')
print 'hello world'
sys.stdout = temp #恢复默认映射关系
print 'nice'

https://blog.csdn.net/he_and/article/details/80675070



#print实现进度条等 ('
'的应用)
#倒计时
count_down = 10  # 设置倒计时时间,单位:秒
for i in range(count_down, 0, -1):
    msg = u"
系统将在 " + str(i) + "秒 内自动退出"
    print(msg, end="")
    time.sleep(1)
end_msg = "结束" + "  "*(len(msg)-len("结束"))  # 如果单纯只用“结束”二字,无法完全覆盖之前的内容
end_msg = "结束"
print(u"
"+end_msg)

#“转圈”功能
count_down = 10  # 设置倒计时时间,单位:秒
interval = 0.25  # 设置屏幕刷新的间隔时间,单位:秒
for i in range(0, int(count_down/interval)):
    ch_list = ["\", "|", "/", "-"]
    index = i % 4
    msg = "
程序运行中 " + ch_list[index]
    print(msg, end="")
    time.sleep(interval)
print(u"
结束" + "  "*len(msg))

#进度条
count_down = 10  # 设置倒计时时间,单位:秒
interval = 1  # 设置屏幕刷新的间隔时间,单位:秒
for i in range(0, int(count_down/interval)+1):
    print("
"+"▇"*i+" "+str(i*10)+"%", end="")
    time.sleep(interval)
print("
加载完毕")


  1. str 和 print 函数 的一些方法
'''
可以用如下的方式,对格式进行进一步的控制:
%[(name)][flags][width].[precision]typecode
(name)为命名
flags可以有+,-,' '或0。+表示右对齐。-表示左对齐。' '为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。
width表示显示宽度
precision表示小数点后精度
'''
print(('%.2d' % 9))  # 09
print(('%02d' % 9))  # 09
print(('% d' % 9))   #  9
print(('% d' % -9))  # -9
print("%10d" % 10)   #         10
print("%-10d" % 10)  # 10
print("%04d" % 5)    # 0005
print("%6.3f" % 2.3) #  2.300


# Python 之 %s%d%f
https://blog.csdn.net/qq_37482544/article/details/63720726


print("I'm %s. I'm %d year old" % ('Vamei', 99))

name = 'Eric'
print(f'Hello, my name is {name}')

print("{1} {0} {1}".format("hello", "world") )

print('{0} is {0:>10.2f}'.format(1.123))  # 取2位小数,右对齐,取10位

print("网站名:{name}, 地址 {url}".format(name="test", url="www.test.com"))
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))
print("I'm %(name)s. I'm %(age)d year old" % {'name':'Vamei', 'age':99})

'''
HTMLTestRunner.py
'''
line = self.HEADING_ATTRIBUTE_TMPL % dict(
    name = saxutils.escape(name),
    value = saxutils.escape(value),
  )

原文地址:https://www.cnblogs.com/amize/p/14991606.html