Python · print输出函数详解

Hello,大家好,我是余同学。我又来更新文章了,希望能帮到大家!

基本用法

输出变量

我们先来讲输出变量,print函数有一个巨大的优点,只要是变量,它都能完整输出,不分类型
不像C语言,还要强制转换类型

a=10 #整型变量
print(a)
b=10.12 #浮点型变量
print(b)
c='CSDN' #字符串变量
print(c)
d=('1', 2, 'hello') #元组变量
print(d)
e=['1', 2, 'hello'] #列表变量
print(e)
f={
    
    'hello':1, 'world':2} #字典变量
print(f)

运行结果:
test1

也可以一次性输出多个变量,中间用逗号,隔开(一定要用英文逗号)

a=10 #整型变量
b=10.12 #浮点型变量
c='CSDN' #字符串变量
d=('1', 2, 'hello') #元组变量
e=['1', 2, 'hello'] #列表变量
f={
    
    'hello':1, 'world':2} #字典变量
print(a,b,c,d,e,f)

在这里插入图片描述

Python默认的间隔符是空格,我们可以更改间格符为其他字符
例如:

a=10 #整型变量
b=10.12 #浮点型变量
c='CSDN' #字符串变量
d=('1', 2, 'hello') #元组变量
e=['1', 2, 'hello'] #列表变量
f={
    
    'hello':1, 'world':2} #字典变量
print(a,b,c,d,e,f,sep="\n") #'\n'表示换行符

test3
把间格符改成一个点.

a=10 #整型变量
b=10.12 #浮点型变量
c='CSDN' #字符串变量
d=('1', 2, 'hello') #元组变量
e=['1', 2, 'hello'] #列表变量
f={
    
    'hello':1, 'world':2} #字典变量
print(a,b,c,d,e,f,sep=".") #'\n'表示换行符

test4

格式字符串

直接上表格

格式 说明
%s 字符串格式
%c 字符及其ASCII码
%d 十进制的有符号整数
%u 十进制的无符号整数
%f 实数(有小数点符号)
%e 实数(科学计数法)

保留小数

注意,这是个很重要的知识点,一定要记住!

ch=2.7182818
print('ch=%.*f' %(3,ch)) #保留3位小数

test5
我们看看Python保留小数时会不会四舍五入

ch=1.1999
print('ch=%.*f' %(1,ch)) #保留1位小数

test6
答:会四舍五入
这点还是十分方便的

还有一种方法,使用format函数

ch=3.1415926
print('ch={:.3f}'.format(ch))

more2


正数输出

输出带正号(+)的数(默认保留6位小数):

ch=2.7182818
print("%+f" %ch)

more1


常见格式字符串的用法

1、输出整数用%d
time=13
print("It is %d o'clock." %time)

test7

2、输出字符串用%s
ch="programming"
print("I love %s ." %ch)

test8

3、输出小数用%f
avg=95.5
print("The average score of our class is %f" %avg)

test9

我们发现,使用格式字符串%f时,Python默认保留6位小数,如果想保留其它位数,可以这么写

avg=95.5
print("The average score of our class is %.*f" %(1,avg))

在这里插入图片描述

结束符与间隔符

结束符

print函数默认的结束符是换行(\n)

for i in range(0,5):
    print("%d" %i) #print(i)

test10

我们可以用end=''函数控制结束符
例如,将结束符改为空格

for i in range(0,5):
    print("%d" %i,end=" ") #结束符为空格

test11

也可以用更多字符来代替结束符

for i in range(0,5):
    print("%d" %i,end="~") #将结束符设为 ~

test12

间隔符

print函数默认的间隔符是空格( )

a=10
b=20
print(a,b)

test12

我们可以用sep=''函数控制间隔符

a=10
b=20
print(a,b,sep="\n")

test13
sep=''函数与end=''函数的括号里都可以填任意字符


猜你喜欢

转载自blog.csdn.net/weixin_45122104/article/details/125958289