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

Python格式化输出

程序员文章站 2022-07-14 23:50:32
...

一、百分号格式化(%)

1.整型输出%d

'my age is %d'% (26)

2.输出字符串%s

'my name is %s' % 'xiaoming'
# 'my name is xiaoming'

3.输出浮点数%f

'His height is %f m' % 1.890
# 'His height is 1.890000 m'

4.保留2位小数

'His height is %.2f m' % (1.890)
# 'His height is 1.89 m'

5.指定占位符宽度(右对齐)

'name:%10s,age:%10d,height:%5.2f' % ('xiaoming',26,1.890)
# 'name:  xiaoming,age:        26,height: 1.89'

6.指定占位符宽度(左对齐)

'name:%-10s,age:%-10d,height:%-5.2f' % ('xiaoming',26,1.890)
# 'name:xiaoming  ,age:26        ,height:1.89 '

7.字符串截取

%.2s表示截取前两位字符串

%10.2s表示10个占位符,截取前两位字符串

'%.2s' % 'hello word'
# 'he'

'%10.2s' % 'hello word'
# '        he'

8、输出%

'今年GDP的增长率:%d%%' % 7
# '今年GDP的增长率:7%'

二、format格式化

1、不设置指定位置,按默认顺序

"{} {}".format("hello", "world")
# 'hello world'

2、指定位置

"{0} {1}".format("hello", "world")
# 'hello world'

3、指定多个位置

"{1} {0} {1}".format("hello", "world")
# 'world hello world'

4、指定变量名传参

"name: {name}, age: {age}".format(name="小新", age=13)
# 'name: 小新, age: 13'

5、元组传参

infos = '钢铁侠', 66, '小辣椒'
'我是{},身价{}亿'.format(*infos)
# '我是钢铁侠,身价66亿'

6、列表传参

my_list = ['python', 'short']
'hello {0[0]}, life is {0[1]}'.format(my_list)
# hello python,life is short

7、字典传参

venom = {'name': '毒液', 'weakness': '火'}
'我是{name},我怕{weakness}'.format(**venom)
# '我是毒液,我怕火'

8、类传参

class AssignValue:

    def __init__(self, value):
        self.value = value

my_value = AssignValue(6)
'value 为: {0.value}'.format(my_value)
# 'value 为: 6'

9.字典转元组传参

venom = {'name': '毒液', 'weakness': '火'}
tup = tuple(venom.values())
'我是{},我怕{}'.format(*tup)

10、数字格式化

保留两位小数

"{:.2f}".format(3.1415926)  # '3.14'

带符号保留小数点后两位

"{:+.2f}".format(3.1415926)  # '+3.14'

不带小数

"{:.0f}".format(3.1415926)  # '3'

数字补零 (填充左边, 宽度为2)

"{:0>2d}".format(5)  # '05'

数字补x (填充右边, 宽度为4)

"{:x<4d}".format(10)  # '10xx'

百分比格式,保留两位小数

"{:.2%}".format(0.25)  # '25.00%'

以逗号分隔数字

"{:,}".format(1000000)  # '1,000,000'

三、python3.6新特性f""

f"hello {'python'}, i {'love'} python"
# 'hello python, i love python'

name = '蜡笔小新'
age = 5
f"my name is {name}, age is {age}"
# 'my name is 蜡笔小新, age is 5'
相关标签: Python 格式化