python的print格式化输出,以及使用format来控制。

本文详细介绍了Python中打印和格式化字符串的各种方法,包括使用%操作符、f-string和format()函数。涵盖了整数、浮点数和字符串的格式化,以及如何控制输出宽度和精度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

20210305

time.strftime("%Y%m%d%H%M%S", time.localtime())
时间格式化

20210206

https://www.runoob.com/w3cnote/python3-print-func-b.html
重点
20210206
https://blog.youkuaiyun.com/a19990412/article/details/80149112
!r
20210205

https://www.jianshu.com/p/7fc0a177fd1f
%r

20210103
在这里插入图片描述

https://blog.youkuaiyun.com/weixin_42427638/article/details/80686294
print %

单独一个% 就表示%

https://blog.youkuaiyun.com/qq_19691995/article/details/84197252
** 字典作为关键字参数传入

20201228

print(’%2d-%02d’%(3,1))中的2和02表示什么意思?

%2d : 输出内容至少占两位且右对齐,输出内容不足两位时在左侧用空格补齐,大于等于两位时正常输出
%02d :输出内容至少占两位且右对齐,输出内容不足两位时在左侧用0补齐,大于等于两位时正常输出

在这里插入图片描述
冒号是填充
在这里插入图片描述
f 是浮点型
2是小数点位数
点号 是小数

https://blog.youkuaiyun.com/u012149181/article/details/78965472

  1,打印字符串(str),利用%s

>>> print ('My name is %s' % ('TaoXiao'))
My name is TaoXiao

 
  • 1
  • 2
  • 3

  2,打印整数,浮点数。

>>> print ("He is %d years old" % (23))         # 整数  %d
He is 23 years old

>>> print ("His height is %f m" % (1.73))       # 浮点数  %f
His height is 1.730000 m

>>> print ("His height is %.2f m" %(1.73))          # 浮点数(指定保留小数点位数)  %.2f
His height is 1.73 m

>>> print ("His height is %.4f m" %(1.73))          # 浮点数(强制保留4位)  %.4f
His height is 1.7300 m

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

  3,利用format。这是官方推荐用的方式,%方式将可能在后面的版本被淘汰。

>>> print('{1},{0},{1}'.format('TaoXiao',18))  # 通过位置传递,相当方便,可以重复,可以换位置。
18,TaoXiao,18

>>> print('{name}: {age}'.format(age=24,name='TaoXiao'))   # 通过关键字传递
TaoXiao: 24

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

  format还有其他很多用法。可以点击这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值