马士兵Python学习笔记_P85_84.格式化字符串

马士兵Python学习笔记_P85_84.格式化字符串

一、格式化字符串

在这里插入图片描述
在这里插入图片描述

二、代码示例

# 格式化字符串
print("-------------------------------(1)占位符: %------------------------------------")
name = "张三"
age = 20
print("我叫%s,今年%d岁。" % (name, age))

print("-------------------------------(1)% 宽度与精度------------------------------------")
print("%d" % 99)
print("%10d" % 99)  # 10表示的是宽度
print("hellohello")

print("%f" % 3.1415926)
print("%.3f" % 3.1415926)   # 保留3位小数
print("%10.3f" % 3.1415926)   # 同时表示宽度和精度。总宽度是10(小数点也算1位),小数点后3位

print("-------------------------------(2){}------------------------------------")
print("我叫{0},今年{1}岁。".format(name, age))
print("-------------------------------(2){} 宽度与精度------------------------------------")
print("{}".format(3.1415926))
print("{0}".format(3.1415926))
print("{0:.3}".format(3.1415926))   # .3 表示的是一共3位数(小数点不算)
print("{0:.3f}".format(3.1415926))   # .3f 表示的是 3位小数
print("{:.3f}".format(3.1415926))   # .3f 表示的是 3位小数
print("{0:10.3}".format(3.1415926))   # 同时表示宽度和精度。总宽度是10(小数点也算1位),一共3位数
print("{0:10.3f}".format(3.1415926))   # 同时表示宽度和精度。总宽度是10(小数点也算1位),小数点后3位

print("-------------------------------(3)f-string------------------------------------")
print(f"我叫{name},今年{age}岁。")
print(f"{3.1415926}")

运行结果:

D:\Environment\Python\Python311\python.exe D:\Environment\PythonWorks\learnpython\马士兵Python\第9章_一串连一串\P85_84.格式化字符串.py 
-------------------------------1)占位符: %------------------------------------
我叫张三,今年20岁。
-------------------------------1% 宽度与精度------------------------------------
99
        99
hellohello
3.141593
3.142
     3.142
-------------------------------2{}------------------------------------
我叫张三,今年20岁。
-------------------------------2{} 宽度与精度------------------------------------
3.1415926
3.1415926
3.14
3.142
3.142
      3.14
     3.142
-------------------------------3)f-string------------------------------------
我叫张三,今年20岁。
3.1415926

Process finished with exit code 0

B站视频链接:https://www.bilibili.com/video/BV1wD4y1o7AS?p=85
参考资料:https://blog.csdn.net/weixin_46883785/article/details/133647716

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值