主页

索引

模块索引

搜索页面

格式化

有两种方法可以格式化文字:

string % data
{}.format (新的写法,推荐使用)
f"{Variable Name}" (Python 3.6之後才有)

第一种搭配的format符號表如下:

符号

种类

%s

字串

%d

十进制整数

%x

十六进制整数

%o

八进制整数

%f

十进制浮点数

%e

以科学计数法表示的浮点数

%g

十进制或科学计数法表示的浮点数

%%

文本值 % 本身

# 方法一实例:

print('%s' % 42)
print('%d' % 42)
print('%x' % 42)
print('%o' % 42)
print('%s' % 7.03)
print('%f' % 7.03)
print('%e' % 7.03)
print('%g' % 7.03)
print('%d%%' % 100)
print('混合搭配文字[%s],以及数字[%f]' % ('我是文字',87))

#可搭配数字做位数控制
print('%10d' % 42)
print('%10.4d' % 42)
print('%10.1f' % 42)
print('%.1f' % 42)

print('%-10d' % 42)
print('%-10.1f' % 42)

# 方法二:

n = 42
f = 7.03
s = 'string cheese'

print('{} {} {}'.format(n, f, s))
print('{2} {0} {1}'.format(n, f, s))
print('{n} {f} {s}'.format(n=42, f=7.03, s='string cheese'))

# 使用字典传入
d = {'n': 42, 'f': 7.03, 's': 'string cheese'}
print('{0[n]} {0[f]} {0[s]} {1}'.format(d, 'other')) #0表示format的第一个参数,1表示第二个参数

# 方法一中的format也可以用在新方法,采用:來做衔接
print('===========分隔线===========')
print('{0:d} {1:f} {2:s}'.format(n, f, s))
print('{n:d} {f:f} {s:s}'.format(n=42, f=7.03, s='string cheese'))
print('===========分隔线===========')
print('{0:10d} {1:10f} {2:10s}'.format(n, f, s))        #指定宽度10,默认右对齐
print('{0:>10d} {1:>10f} {2:>10s}'.format(n, f, s))     #右对齐
print('{0:<10d} {1:<10f} {2:<10s}'.format(n, f, s))     #左对齐
print('{0:^10d} {1:^10f} {2:^10s}'.format(n, f, s))     #置中对齐
print('{0:>010d} {1:>10.4f} {2:>10.4s}'.format(n, f, s)) #与旧方法不同,整数沒有经度设定项
print('{0:!^20s}'.format('BIG SALE'))                   #指定填充符号

主页

索引

模块索引

搜索页面