欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python学习-22 字符串格式化

程序员文章站 2022-06-24 11:12:39
格式化包括:百分号方式和format方式 1.百分号 - %s (%.4s 表示截取了4个字符) 传单个值: 例如: 运行结果: 传多个值: 运行结果: - %d (只能传数字) 运行结果: -打印浮点数 运行结果: -打印百分比 运行结果: -键值 运行结果: -其他方法 运行结果: 2.form ......

格式化包括:百分号方式和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