Python自动化开发数据类型之字符串格式化

Python 数据类型-字符串格式化

数据类型之字符串格式化(字符串拼接)

1.字符串格式化-%用法

例1:打印输出字符串

#!/usr/bin/env python
# -*- coding:utf-8 -*-

msg01="I like %s" %"basketball"
print(msg01)
View Code

代码运行结果:

I like basketball

例2:打印输出字符串

#!/usr/bin/env python
# -*- coding:utf-8 -*-

msg01="I like %s and %s" %("basketball","pong")
print(msg01)
View Code

代码运行结果:

I like basketball and pong

例3:打印输出整型

#!/usr/bin/env python
# -*- coding:utf-8 -*-
print("I am %d years" %(12))
View Code

代码运行结果:

I am 12 years

例4:打印输出浮点数

#!/usr/bin/env python
# -*- coding:utf-8 -*-

print("percent %f" %(99.23680796))
View Code

代码运行结果:

percent 99.236808

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#打印输出浮点数,默认保留六位小数;保留1位小数
print("percent %.1f" %(99.23680796))
View Code

代码运行结果:

percent 99.2

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#打印输出浮点数,默认保留六位小数;保留2位小数
print("percent %.2f" %(99.23680796))
View Code

代码运行结果:

percent 99.24

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#打印输出浮点数,默认保留六位小数;保留2位小数,打印%
print("percent %.2f%%" %(99.23680796))
View Code

代码运行结果:

percent 99.24%

2.字符串格式化-format用法

format格式化用法

例1:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

str01="I am {} years,I like to play {},I hard work {}!" .format(12,"basketball","always")
print(str01)
View Code

代码运行结果:

I am 12 years,I like to play basketball,I hard work always!

例2:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

str01="I am {2} years,I like to play {0},I hard work {1}!" .format("basketball","always",12)
print(str01)
View Code

代码运行结果:

I am 12 years,I like to play basketball,I hard work always!

例3:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#字符串格式化(字符串拼接)用法:字典形式
str01="I am {age} years,and my brother also is  {age} ,I hard work {fuci}!" .format(fuci="always",age=13)
print(str01)
View Code

代码运行结果:

I am 13 years,and my brother also is  13 ,I hard work always!

例4:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
str01="I am {age} years,and my brother also is  {age} ,I hard work {fuci}!" .format(**{"age":12,"fuci":"always"})
print(str01)
View Code

代码运行结果:

I am 12 years,and my brother also is  12 ,I hard work always!

例5:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#字符串格式化(字符串拼接)用法:进制转换
str02="the numbers:{:b},{:d},{:o},{:f}" .format(12,10,16,92.392786613)
print(str02)
View Code

代码运行结果:

the numbers:1100,10,20,92.392787

你不向我走来,我便向你走去。
原文地址:https://www.cnblogs.com/renyongbin/p/15734970.html