Python 字符串格式化
2016-07-13 23:46
337 查看
1.用%s来表示
输出:
alex %% %%
alex SB %% #一旦前面出现过%占位符,后面只能用%%表示一个%
2.用format格式化
s = "welcome %s to login %s"%("alex","china") print (s) s = "welcome %(name)s to login %(city)s"%{"name":"alex","city":"wuhan"} print (s)
s = "%10s is %+10d years old"%("alex",-10) print (s) alex is -10 years old 解释:第一个字符串占10个字符,右对齐,第二个也占10个字符,右对齐,+号正数前面加+,负数前面加-。
s = "The pi is %.4f"%(3.1415926) print (s) The pi is 3.1416 或者是下面的写法
s = "The pi is %(p).4f"%{"p":3.1415926}
s = "The pi is ====%c=====%x======%o"%(65,15,15) print (s) The pi is ====A=====f======17
s = "alex %% %%" print (s) s1 = "alex %s %%%%"%("SB") print (s1)
输出:
alex %% %%
alex SB %% #一旦前面出现过%占位符,后面只能用%%表示一个%
2.用format格式化
s = "----->{0}------>{1}------>{0}".format("alex",10) print (s) ----->alex------>10------>alex
s = "----->{name:s}------>{age:d}------>{name:s}".format(name="alex",age=10) print (s) ----->alex------>10------>alex
s = "-----{:9^20s}=====".format("alex") print (s) -----99999999alex99999999===== 解释:字符串宽度为20,居中放置,不足的部分用9来填充
s2 = "======{:*<20s}======{:+d}======{:#b}".format('alex',123,15) print (s2) ======alex****************======+123======0b1111 解释:#号只是给b,o,x前面加上0b,0o,0x的符号
s3 = "{:.2%}".format(0.234567) print (s3) 23.46%
s = "{} is {} years old".format("alex",18) print (s) s1 = "{} is {} years old".format(*["alex",18]) print (s1) s2 = "{name} is {age} years old".format(**{"name":"alex","age":18}) print (s2)
相关文章推荐
- python中self和__init__的含义 + 为何要有self和__init__
- Python 爬虫入门(二)—— IP代理使用
- Python 调试
- Python 错误处理
- Python 面向对象高级编程――使用枚举和元类
- Python爬虫总结
- Python 面向对象高级编程――定制类
- Python 面向对象高级编程――多重继承
- Python 面向对象高级编程――使用@property
- Python 面向对象高级编程――使用__slots__
- Python语言及其应用 第2章
- Python 面向对象编程――获取对象信息
- Python 面向对象编程――继承和多态
- Python 面向对象编程——访问控制
- Python 面向对象编程——类和实例
- Python + Android + Uiautomator自动化测试
- python学习例程1-helloword
- 不用加减乘除做加法中Python存在的bug
- 使用uiautomator的python封装进行android的UI测试
- python之socket编程(二)