Python学习(三)格式化输出

字符串格式化输出:https://blog.csdn.net/py_1995/article/details/84031480

1,%s:占位符,将其他类型强转为string类型,是str(变量)的缩写

name='张三';
age=12;
sex=''
print("姓名:%s
年龄:%s
性别:%s"%(name,age,sex));   %s占变量的位置

2,%d:占位符,将其他类型强转为int类型,是int(变量)的缩写,不能占位非整数变量,

3,%f:占位符,占位浮点数,%.nf(根据四舍五入输出带小数点后n位小数的数字)

复制代码
movie='《阿甘正传》';
price=23.6;
num=3;
message='''欢迎看电影:
    电影:%s
    票价:%.2f
    票数:%d
''' %(movie,price,num);
print(message);
复制代码

4,使用format函数

复制代码
movie='《阿甘正传》';
price=23.6;
num=3;
message='''欢迎看电影:
    电影:{}
    票价:{}
    票数:{}
''' .format(movie,price,num);      //.为字符串调用format函数
print(message);
复制代码

原文地址:https://www.cnblogs.com/lq13035130506/p/12570841.html