python format函数实例_【Python】-String的Format格式规约函数及实例

#字符串格式规约

#format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]

#参数详解

#fill ::= ,填充字符

#align ::= "<" | ">" | "^"左对齐,右对齐,右对齐

#sign ::= "+" | "-" | " "数字是否带正负标识

#width ::= integer 长度

#precision ::= integer 小数位数

#type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" 类型

s="This is a test string";

print("{0}".format(s));

print("{0:>25}".format(s));

print("{0:^25}".format(s));

print("{0:<25}".format(s));

print("{0:.10}".format(s));

print("{0:*=12}".format(8749203));

print("{0:*=12}".format(-8749203));

print("{0:*>12}".format(8749203));

print("{0:*^12}".format(8749203));

print("{0:*<12}".format(8749203));

print("b:{0:b},0:{0:0},x:{0:x},X:{0:X})".format(8749203));

print("{0:,}".format(8749203));

import math;

amout=(10**3)*math.pi

print("[{0:12.2e}],[{0:12.2f}]".format(amout));

print("[{0:*<12.2e}],[{0:#<12.2f}]".format(amout));

#个人感觉以下例子比较完全,所以直接转载过来。

print('{0}, {1}, {2}'.format('a', 'b', 'c'))

print('{}, {}, {}'.format('a', 'b', 'c') ) # 3.1+ only

print('{2}, {1}, {0}'.format('a', 'b', 'c'))

print('{2}, {1}, {0}'.format(*'abc')) # unpacking argument sequence

print( '{0}{1}{0}'.format('abra', 'cad'))

print('Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W'))

coord = {'latitude': '37.24N', 'longitude': '-115.81W'}

print('Coordinates: {latitude}, {longitude}'.format(**coord))

coord = (3, 5)

print('X: {0[0]}; Y: {0[1]}'.format(coord))

print("repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2'));

print('{:<30}'.format('left aligned'))

print('{:>30}'.format('right aligned') )

print('{:^30}'.format('centered'))

print('{:*^30}'.format('centered')) # use '*' as a fill char

print('{:+f}; {:+f}'.format(3.14, -3.14)) # show it always

print('{: f}; {: f}'.format(3.14, -3.14) ) # show a space for positive numbers

print('{:-f}; {:-f}'.format(3.14, -3.14) )# show only the minus -- same as '{:f}; {:f}'

print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42))

# with 0x, 0o, or 0b as prefix:

print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42))

points = 19

total = 22

print('Correct answers: {:.2%}.'.format(points/total))

for align, text in zip('<^>', ['left', 'center', 'right']):

print('{0:{fill}{align}16}'.format(text, fill=align, align=align))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值