Python print 格式化輸出與排版

本篇將介紹如何使用 Python print 格式化輸出與排版,在寫 python 程式有時常會用到 print,順便在這邊作個紀錄。

以下內容分為這幾部份,

  • print 基本輸出
  • print 基本輸出 (format用法)
  • print 對齊排版
  • print 對齊排版 (format用法)
  • print 輸出浮點數到小數點兩位
  • print 輸出 % 百分比符號
  • Python print 不換行

Python 如果想用 print 輸出字串,可以用下列方式:

1
2
s1 = 'hello'
print('%s world' % s1)

輸出:

1
hello

也可以這樣寫,用 + 來連接字串,可以一直連接下去

1
2
3
s1 = 'hello'
s2 = ' world'
print(s1 + s2)

Python 如果想用 print 輸出字元,可以用 %c 格式化字元輸出的方式:

1
2
c1 = chr(65)
print('%c' % c1)

輸出:

1
A

Python 如果想用 print 輸出整數,可以用 %d 格式化整數輸出的方式:

1
2
n = 123
print('%d' % n)

輸出:

1
123

Python 如果想用 print 輸出浮點數(預設輸出到小數點第六位),可以用 %f 格式化浮點數輸出方式:

1
2
n = 123.4
print('%f' % n)

輸出:

1
123.400000

Python 如果想用 print format 輸出字串,可以用下列方式,
分別為 不數字編號,帶數字編號,自訂順序,重複多次輸出

1
2
3
4
5
6
7
s1 = 'hello'
s2 = 'world'

print('{} {}'.format(s1, s2)) # 不數字編號
print('{0} {1}'.format(s1, s2)) # 帶數字編號
print('{1} {0}'.format(s1, s2)) # 自訂順序
print('{0} {1} {0}'.format(s1, s2)) # 重複多次輸出

輸出:

1
2
3
4
5
hello
hello world
hello world
world hello
hello world hello

Python 如果想用 print format 輸出字元,可以用下列方式:

1
2
c1 = chr(65)
print('{}'.format(c1))

Python 如果想用 print format 輸出整數,可以用下列方式:

1
2
n = 123
print('{}'.format(n))

輸出:

1
123

Python 如果想用 print format 輸出浮點數,可以用下列方式:

1
2
n = 123.4
print('{}'.format(n))

輸出:

1
123.4

Python 如果想用 print 字串對齊(預設靠右對齊),可以用下列方式:

1
2
s1 = 'hello'
print('[%10s]' % s1)

輸出:

1
[     hello]

Python 如果想用 print 字串靠左對齊,可以用下列方式:

1
2
s1 = 'hello'
print('[%-10s]' % s1)

輸出:

1
[hello     ]

Python 如果想用 print format 字串對齊(預設靠左對齊),可以用下列方式:

1
2
s1 = 'hello'
print('[{:10}]'.format(s1))

輸出:

1
[hello     ]

Python 如果想用 print format 字串靠右對齊,可以用下列方式:

1
2
s1 = 'hello'
print('[{:>10}]'.format(s1))

輸出:

1
[     hello]

Python 如果想用 print format 字串置中對齊,可以用下列方式:

1
2
s1 = 'hello'
print('[{:^10}]'.format(s1))

輸出:

1
[  hello   ]

Python 如果想用 print format 字串靠左對齊,可以用下列方式:

1
2
s1 = 'hello'
print('[{:<10}]'.format(s1))

輸出:

1
[hello     ]

Python 如果想用 print 輸出浮點數到小數點兩位,例如:20.12,可以用下列這個方式:

1
2
number = 20.1234
print('%.2f' % number)

輸出:

1
20.12

Python 如果 print 後面還想輸出 % 百分比符號 percentage,例如:20.12 %,可以這樣寫

1
2
rate = 20.12
print('%.2f' % rate + chr(37))

輸出:

1
20.12%

Python print 不換行

Python print 不換行的話方法如下,就是將結尾的字元設為空,

1
print('hello world', end='')

Python 預設 print 是會換行的,也就是將結尾的字元設為換行字元 '\n',預設跟下面的效果一樣,

1
print('hello world', end='\n')

以上就是 Python print 的介紹,下一篇會來介紹 Python 取得鍵盤輸入

參考
https://www.itread01.com/content/1548549397.html
https://stackoverflow.com/questions/2075128/python-print-all-floats-to-2-decimal-places-in-output
https://www.codespeedy.com/how-to-print-percentage-sign-in-python/
https://stackoverflow.com/questions/5306756/how-to-print-a-percentage-value-in-python

其它相關文章推薦
Python 新手入門教學懶人包
Python 讀檔,讀取 txt 文字檔
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 建立多執行緒 thread
Python OpenCV resize 圖片縮放
Python OpenCV 顯示camera攝影機串流影像
Python 快速建立簡單網頁伺服器 http websever
Python 建立簡單的 Tornado Web
[Python小專案] Tornado+PyAutoGUI 多媒體控制播放的網頁