Python学习笔记:格式化输出之f-string、format、%

Python学习笔记:格式化输出之f-string、format、%

一、%占位符

1.说明

# 符号代表意义
%s -- 字符串
%10s -- 指定长度 左填充
%-10s -- 指定长度 右填充

%f -- 浮点数
%.2f -- 保留2位小数点

%d -- 整数

2.实操

a = 'Name'
b = 'Hider'
c = 100
d = 1.80

print("My %s is %s." % (a, b))
# My Name is Hider.

print("My %s is %s. And my age is %d. My height is %f." % (a, b, c, d))
# My Name is Hider. And my age is 100. My height is 1.800000.

%f 默认精度是保留后6位,可通过 %.2f 设置。

print("My %s is %s. And my age is %d. My height is %.2f." % (a, b, c, d))
# My Name is Hider. And my age is 100. My height is 1.80.

字符串长度填充。

# 左填充
print('%10s' % ('Hider'))  #      Hider

# 右填充
print('%-10s' % ('Hider')) # Hider  

二、f-string格式化

f-string 直接使用变量名填充句子当中的内容。

Python 3.6 及以后版本支持 f-string 格式化输出字符串。优先推荐!!!

a = 'Name'
b = 'Hider'
print(f'My {a} is {b}.')
# My Name is Hider.

print(f'计算结果为:{2*5 + 3*10}')
# 计算结果为:40

string_test = 'ABC'
print(f'It\'s {string_test.lower()}')
# It's abc

三、format关键字

1.格式化输出

format 关键字用来格式化输出字符串。不同入参情况:

  • 不指定位置
a = 'Name'
b = 'Hider'
c = 100
d = 1.80

print('My {} is {}.'.format(a,b))
# My Name is Hider.

位置默认开始从 0 计算,然后对应位置填入数据。

  • 指定位置
a = 'Name'
b = 'Hider'
c = 100
d = 1.80

print('My {0} is {1}. And my age is {2}.'.format(a,b,c))
# My Name is Hider. And my age is 100.

print('My {1} is {2}. And my age is {0}.'.format(a,b,c))
# My Hider is 100. And my age is Name.
  • 关键字配对
print('My {a} is {b}. And my age is {c}.'.format(a=10,b=20,c=30))
# My 10 is 20. And my age is 30.
  • 字典参数
dic = {'a':10, 'b':20, 'c':30}
print('My {a} is {b}. And my age is {c}.'.format(**dic))
# My 10 is 20. And my age is 30.

  • 列表参数
lis = ['a','b','c']
s = 'i like {} and {} and {}.'.format(*lis)
print(s)
# i like a and b and c.

2.精度

pi = 3.1415926535
print('{:.2f}'.format(pi)) # 3.14
print('{:+.3f}'.format(pi)) # +3.142
print('{:.2%}'.format(pi)) # 314.16%

3.千分位分隔符

主要用于货币数据的格式化输出。

a = 1000000000
print('{:,}'.format(a)) # 1,000,000,000

# 添加货币符号
print('${:,}'.format(a)) # $1,000,000,000

参考链接:【Python】全方面解读Python的格式化输出

参考链接:万字长文,史上最全Python字符串格式化讲解

上一篇:Go sync.Map


下一篇:GBase 8a Mpp Cluster集群产品性能优化篇之关联顺序