###### tags: `python` >[name=彥亨林] # Python 延伸閱讀: Print --- ## print function * 語法: ***print(object(s), sep=separator, end=end, file=file, flush=flush)*** * **object(s)** 任何你想要輸出的物件,例如:=="hello world"== , ==5== ,而這些物件在 print 前會轉成 str type,這裡的轉型是在 print function 裡執行的,所以你 function 外的物件 type 不會因為傳進 print function 就改變 * **sep** 物件跟物件之間如何區開,預設為空白鍵 ==' '==,你也可以做更改,將它改成你喜歡的區開方式,例如: ==,== * `print("hello","world")` 運行結果為 ![](https://i.imgur.com/0vtXQkS.png) * 改成以 ==,== 做區開 `print("hello","world",sep=',')` 運行結果為 ![](https://i.imgur.com/8CJA9gQ.png) * **end** print 完物件後,要用什麼當作結尾,預設是用換行字符 =='\n'== 當作結尾,當然你也可以做更改,例如: * ```python= print("hello") print("world") ``` 運行結果為 ![](https://i.imgur.com/L19OCp0.png) * 改成空白字元 ==' '== 當作結尾 ```python= print("hello",end=' ') print("world") ``` 運行結果為 ![](https://i.imgur.com/JNo1aim.png) * **file** 預設為 ==sys.stdout==,這個有興趣的可以自己去查查看這是什麼意思 * **flush** 以 boolean 值做操作,flushed (True) or buffered (False),預設為 False,這個也是有興趣可以去查查 flushed 或 buffered 是什麼,在這裡就不多做解釋,因為牽涉的機制比較複雜 ## Print 格式 * **問題** 1. 我們在輸出字串時常常會面臨一種窘境,那就是輸出的字串,永遠是靠左對齊的,執行以下的 code ```python= print(123) print(123456789) print(12345678) print(12345) ``` ![](https://i.imgur.com/IjiDBTG.png) 就能發現,我印出來的字永遠是向左對齊的,然而壞處是我不能一眼就看出這四個數字的實際大小關係是如何,原因是他的個位數不是對齊的。 2.或是人名跟物品的清單,常常會因為名子的長度的不同導致,人名跟物品不能很清楚的區隔開來,以下面的 code 為例: ```python= print("henry","book") print("jack","mortor") print("geneous","bus") ``` ![](https://i.imgur.com/RLtfBAT.png) * **解決辦法** 指定輸出的字串要在螢幕從左數來的第幾格輸出 * 比如果想在螢幕數從左數來的第十格輸出 hello ```python= print("%10s"%"hello") ``` ![](https://i.imgur.com/BNeSnWo.png) * 上述 code 含意是, =="hello"== 這個字串,以 ==%10s== 的方式輸出,10代表輸出的字串長度為10,而且從第10格開始填入字元,hello 為五個字元,所以還會剩下五個字元沒填入字,沒填入的字以空白字元代替,==s== 代表,填入的字是字串,如果要改成整數,則要使用 ==d== * **問題1.** 改寫 ```python= print("%10d"%123) print("%10d"%123456789) print("%10d"%12345678) print("%10d"%12345) ``` ![](https://i.imgur.com/NToVM9K.png) 可以看到輸出的數字很整齊地向右對齊 * 那如果今天我想要輸出10格字串,但卻要從左邊開始輸出的話,只要將 ==%10s== 改成 ==%-10s== 就可以了 * **問題2.** 改寫 ```python= print("%-10s"%"henry","book") print("%-10s"%"jack","mortor") print("%-10s"%"geneous","bus") ``` ![](https://i.imgur.com/6nJYgmw.png) ## 參考資料 * [w3school print function](https://www.w3schools.com/python/ref_func_print.asp) * [Python 字串格式化教學與範例](https://officeguide.cc/python-string-formatters-tutorial/)