python学习-22 字符串格式化
2024-09-01 15:20:47
格式化包括:百分号方式和format方式
1.百分号
- %s (%.4s 表示截取了4个字符)
传单个值:
例如:
print('i am %s sex boy is ljj'%123)
运行结果:
i am 123 sex boy is ljj Process finished with exit code 0
传多个值:
print('i am %s sex boy is %s'%('','ss'))
运行结果:
i am 13 sex boy is ss Process finished with exit code 0
- %d (只能传数字)
a= 'i am %s, she is %d'%('xm',123)
print(a)
运行结果:
i am xm, she is 123 Process finished with exit code 0
-打印浮点数
a= 'abc %.2f'%99.45678 # .2表示保留小数点后2位(四舍五入)
print(a)
运行结果:
abc 99.46 Process finished with exit code 0
-打印百分比
a= 'abc %.2f %%'%99.45678
print(a)
运行结果:
abc 99.46 % Process finished with exit code 0
-键值
a= "i am %(name)s ,and age is %(age)d" % {"name":"ljj","age":18}
print(a)
运行结果:
i am ljj ,and age is 18 Process finished with exit code 0
-其他方法
a= "i am %(name)-60s aabbcc" % {"name":"ljj"} #左对齐60格(+右对齐)
print(a)
运行结果:
i am ljj aabbcc Process finished with exit code 0
2.format方式
-传值
a= "i am {},age {},{}" .format("xm",18,123)
print(a)
运行结果:
i am xm,age 18,123 Process finished with exit code 0
-根据索引取值
a= "i am {1},age {0}" .format("xm",18,123)
print(a)
运行结果:
i am 18,age xm Process finished with exit code 0
-
a= "i am {name},age {age} " .format(name="xm",age=18)
print(a)
运行结果:
i am xm,age 18 Process finished with exit code 0
最新文章
- SSH实例(2)
- .NET安全审核检查表
- Memcached和Redis对比和适用场景
- 70多G的Kindle电子书合集
- IOS之UI--小实例项目--添加商品和商品名(纯代码终结版)
- bzoj 2741 分块+可持久化trie
- POJ-3026 Borg Maze---BFS预处理+最小生成树
- 628. Maximum Product of Three Numbers
- windows下实现win32俄罗斯方块练手,编程的几点心得
- 微信小程序之初探(常见语法 VS vue)常见问题(点击不生效,数据绑定)
- Python3从零开始爬取今日头条的新闻【一、开发环境搭建】
- Python进阶之函数式编程
- Xilinx原语学习之时钟资源相关原语
- java基础编程
- .NET并行计算和并发3.2-多线程调用Invoke
- Python装饰器举例分析
- c#实现windows远程桌面连接程序代码
- 最好的PHP博客系统
- 第八届蓝桥杯JavaB---承压计算
- Android+Handler+Thread 那些事儿
热门文章
- mybatis xml中是sql语句报错: Error creating document instance. Cause: org.xml.sax.SAXParseException: The
- httpencode编码
- Cookie 概述
- Windows 下 把EXE 程序变成服务运行
- 反查BOM, 找出它的上阶
- LeetCode_121. Best Time to Buy and Sell Stock
- (三)UML之类图关系
- 第六章 Realm及相关对象——《跟我学Shiro》
- Flutter 原生TabBar切换标签页示例
- Flutter easyrefresh示例 上拉加载+下拉刷新