1.print()函数基本用法
print(*objects, sep=' ', end='\n', file=sys.stdout)
objects – 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
sep – 用来间隔多个对象,默认值是一个空格。
end – 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
file – 要写入的文件对象。
2.格式化输出
多个参数的输出
s = 'Duan Yixuan'
x = len(s)
print('The length of %s is %d' % (s,x))
#和C语言的区别在于,Python中格式控制符和转换说明符用%分隔,C语言中用逗号。
python常用格式字符
%s 字符串采用str()的显示
%x 十六进制整数
%r 字符串(repr())的显示
%e 指数(基底写e)
%c 单个字符
%E 指数(基底写E)
%b 二进制整数
%f,%F 浮点数
%d 十进制整数
%g 指数(e)或浮点数(根据显示长度)
%i 十进制整数
%G 指数(E)或浮点数(根据显示长度)
%o 八进制整数
%% 字符%
数字:设置精度和宽度
PI = 3.141592653
print('%10.3f' % PI) #字段宽10,精度3
#输出: 3.142
#精度为3,所以只显示142,指定宽度为10,所以在左边需要补充5个空格,以达到10位的宽度 000003.142
转换标志:
-表示左对齐;%-f%x
+表示在数值前要加上正负号;%+10.3f%x
" "(空白字符)表示正数之前保留空格();%010f%x
0表示转换值若位数不够则用0填充。
3.输出列表元素
print(i,end=" ") # end=" ",以空格为分隔符,输出不换行
print(i) # 输出换行
# print()函数的输出
a=[1,2,3,4,'a','c','d','f','v','s']
# 1.一行一个
for i in a:
print(i)
print('\n')
# 2.以空格为分隔符,不换行
for i in a:
print(i,end=' ')
print('\n')
# 3.以换行符为分隔符,最后没有空格
print(" ".join(str(a))) # join()函数迭代对象是str,需要把元素统一转换成str
print('\n')
# 4.判断这个元素是不是列表的最后一个元素,根据判断结果输出分隔符
for i in a:
print(i,end=' ' if i != a[-1] else '')
print('\n')
# 5.一行输出列表
print(a,sep=' ')
1
2
3
4
a
c
d
f
v
s
1 2 3 4 a c d f v s
[ 1 , 2 , 3 , 4 , ’ a ’ , ’ c ’ , ’ d ’ , ’ f ’ , ’ v ’ , ’ s ’ ]
1 2 3 4 a c d f v s
[1, 2, 3, 4, ‘a’, ‘c’, ‘d’, ‘f’, ‘v’, ‘s’]
join()函数
将一个包含多个字符串的可迭代对象,转为用分隔符s连接的字符(不能是数字)
上述方法3就是利用join()函数 【” “.join(字符串列表/字符串元素) 】
[ 1 , 2 , 3 , 4 , ’ a ’ , ’ c ’ , ’ d ’ , ’ f ’ , ’ v ’ , ’ s ’ ]
3.format函数
# format函数
# {引用的部分} 在代码快中呈现蓝色,如果不是蓝色,说明语法错误
# 1.通过位置填充字符串
# 同一个参数可以填充多次
# 不输入数字{}则按照默认顺序填充
a='ross'
b='richael'
c='chandle'
d=2
print('the old friends mumber include {0}、{2},{1} and monic ,i love it'.format(a,c,b))
# 2.通过key填充
print('the old friends mumber include {a}、{b},{c} and monic ,i love it,yeah{d}'.format(a=a,c=c,b=b,d=d))
# 3.通过列表填充
list=['ross','monica',2]
print('{friends[0]} and {friends[1]} is family,{name[2]} people'.format(friends=list,name=list))
# 4.通过字典填充
dic={'brother':'ross',
'sister':'monica',
'girlfriend':'richael'
}
print('{names[brother]} and {names[girlfriend]} is a loving couple '.format(names=dic))
print(dic['girlfriend'])
## 注意names[brother] names['brother']
# 5.通过类的属性填充
class OldFriends:
number=6
door=902
sister='monica'
brother='ross'
couple='qq and mm'
print('{OldFriends.brother} and {OldFriends.sister} is a couple'.format(OldFriends=OldFriends))
本文介绍了Python中的print()函数基础用法,包括如何输出多个对象、自定义间隔和结尾。接着讨论了格式化输出,如%s,%d等格式字符的使用,并展示了join()函数在输出列表元素时的作用。最后,文章详细讲解了format函数的四种用法,包括位置填充、键填充、列表和字典填充,以及类的属性填充。
2662






