Python %和format的用法
一、%的用法
1.整数的输出
#八进制oct %o print('%o' % 10) #12 #十进制dec %d print('%d' % 1) #10 #十六进制hex %x print('%x' % 1) #a
2.浮点型数据输出
# %f 默认保留6位小数 %.1f 保留1位小数 print('%f,%.1f' % (1.11,1.11)) #1.110000,1.1 #%e 默认保留6位小数,用科学计算法 ,%.1保留1位小数 print('%e,%.1e' % (1.11,1.11)) #1.110000e+00,1.1e+00 #%g 在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法 print('%g,%.1g' % (1.1111111,1.1111)) #1.11111,1 print('%g,%.1g' % (11111111.1,11111111)) #1.11111e+07,1e+07
3.字符串输出
#%s字符串输出 print('%s' % 'hi') #hi #%ns 右对齐,n位占位符,不够则补位 print('%10s' % 'hi,hi,hi') # hi,hi,hi #%-ns 左对齐,n位占位符,不够则补位 print('%-10s' % 'hi,hi,hi') #hi,hi,hi print('%-10s' % 'hi,hi,hi,hi,hi') #hi,hi,hi,hi,hi #%.ns 截取n个字符串 print('%.2s' % 'hi,hi,hi') #hi #%n.ns 整数部分是占位符,小数点是截取n个字符串 print('%10.2s' % 'hi,hi,hi') # hi
4.format用法
该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符
#‘{}’ 最简单格式
print('{},{}'.format('hello','world')) #hello,world
#位置编号
print('{0},{1}'.format('hello','world'))
print('{0},{1},{0}'.format('hello','world')) #位置编号,可以输出多次 hello,world,hello
print('{1},{1}'.format('hello','world')) #world,world
#关键词
print('{a},{b}'.format(a='hello',b='world')) #a,b关键词 hello,world
较常用的百分比%输出和会计千分位额输出法
print('{:.2%}'.format(0.12354)) #百分比 print('{:,}'.format(123456789)) #会计千位分隔符 print('{:.2f}'.format(31.31412)) #保留2位小数
使用list和dict映射
#list映射,格式是0[i] l=list('abcd') print('{0[0]},{0[1]},{0[2]},{0[3]}'.format(l)) #dict ,格式是key引用 dict={'name':'tom','age':20} print('name is {name},age is {age}'.format(**dict)) #name is tom,age is 20
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人