python学习-22 字符串格式化

2019-07-24 09:11:06来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

格式化包括:百分号方式和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'%('13','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

 


原文链接:https://www.cnblogs.com/liujinjing521/p/11119774.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python学习-20 集合

下一篇:Python基础笔记(数据类型和变量)