print()函数是python中非常重要的内置函数,其基本语法与参数如下:

print(*objects, sep=' ', end='\n', file=None, flush=False)

(1)*objects可以接收多个参数,sep默认以空格分隔

  • print(1,2,3)
  • 1 2 3

(2)sep指定特殊字符"."

  • a="www"
    b="njxzc"
    c="edu"
    d="cn"
    print(a,b,c,d,sep='.')
    
  • www.njxzc.edu.cn

(3)end指定结束标记,默认是换行"\"

  • a="abcd"
    for w in a:
        print(w)
  • a
    b
    c
    d
    

(4)end指定空格分隔

  • a="abcd"
    for w in a:
        print(w,end=' ')
  • a b c d 

(5)file参数是输出目标(文件对象),encoding用于指定编码方式,此处若不指定,可能在读取a.txt的时候,汉字会出现乱码

  • f=open('a.txt','a',encoding='utf-8')
    print("江苏省会", "南京", sep=" is :", end="!\n", file=f)
  • 
    江苏省会 is :南京!

(6)Python中print()函数的flush参数用于控制输出缓冲区的刷新行为。当设置为True时,会强制立即将输出内容刷新到目标设备(如控制台或文件),而不等待缓冲区满或程序结束

import time
for i in range(10):
    print(f'\rProgress: {i*10}%', end='', flush=True)
    time.sleep(0.5)
Progress: 90%

(7)f-string

a="Hello"
b="World"
c=3*5
d=7/2
print(f"a is {a}\n b is {b}\n c is {c}\n d is {d}")
a is Hello
 b is World
 c is 15
 d is 3.5

(8).format()

subject="English"
score=98
print("Subject:{}\nscore:{}".format(subject,score))
Subject:English
score:98

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐