[Python] 格式化輸出 %s 和 format() 用法整理

整理一下常用的方法
不打多餘的說明,作為查表用途

基本用法

a = '第一個變數: %s, 第二個變數: %s' % ('a''b')
b = '第一個變數: {}, 第二個變數: {}'.format('a''b')
c = '第二個變數: {0}, 第一個變數: {1}'.format('a''b')

a: 第一個變數: a, 第二個變數: b
b: 第一個變數: a, 第二個變數: b
c: 第二個變數: b, 第一個變數: a


填充和對齊

a = '%10s' % ('a')
b = '%-10s' % ('b')
c = '{:10}'.format('c')
d = '{:>10}'.format('d')
e = '{:<10}'.format('e')
f = '{:^10}'.format('f')
g = '{:_<10}'.format('g')
h = '{:*<10}'.format('h')
i = '{:@<10}'.format('i')

a: '         a'
b: 'b         '
c: 'c         '
d: '         d'
e: 'e         '
f: '    f     '
g: 'g_________'
h: 'h*********'
i: 'i@@@@@@@@@'


截斷

a = '{:8}'.format('syuan')
b = '{:8}'.format('http://syuanme.blogspot.com/')
c = '{:.8}'.format('http://syuanme.blogspot.com/')
d = '{:.8}'.format('syuan')
e = '{:*>12.3}'.format('Benjamin')
f = '%.8s' % ('http://syuanme.blogspot.com/')
g = '%12.8s' %('http://syuanme.blogspot.com/')

a: 'syuan   '
b: 'http://syuanme.blogspot.com/'
c: 'http://s'
d: 'syuan'
e: '*********Ben'
f: 'http://s'
g: '    http://s'


格式化數字和浮點數

a = '%d' % (3000)
b = '{:$>5d}'.format(3000)
c = '{:f}'.format(3.1415926)
d = '{:f}'.format(3.1415924)
e = '{:f}'.format(314)
f = '%.2f' % (3.1415)
g = '{:.2f}'.format(3.1415)
h = '{:$>5.2f}'.format(3.1415)

a: '3000'
b: '$3000'
c: '3.141593'
d: '3.141592'
e: '314.000000'
f: '3.14'
g: '3.14'
h: '$3.14'


reference: https://codingnote.cc/zh-tw/p/66562

留言

張貼留言

熱門文章