項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Python 字串處理 #1】python – string format, str.format() 個人常用參數整理 (updated: 2022/12/19)

前言

2022/12/19,本人已改只用 f-string 了,這篇是舊文。

留著給需要的人參考吧,不過還是大推在 python 3.6 版本更新的 f-string !

有時候碰到要在 3.6 版本以前的 python 開發還是用的到啦XD (只是機會超少XD)

基本用法

s1 = "Hello"
s2 = "world!"
s = "{} {}".format(s1, s2) # Hello world!

常使用參數

變數

"{:d}".format(1) # 整數
"{:f}".format(2.0) # 浮點數

格式、對齊

可以使用 > ^ < 這三種符號對齊,常用為「 > 向右對齊」

"{:>8d}".format(1) # 向右對齊,總長度8
"{:0>8d}".format(1) # 向右對齊,總長度8,並補0

常用功能:因為檔名的編號如果是 1.jpg, 2.jpg, … 10.jpg, 11.jpg
會因為先抓到第一個數字1,而讓「2.jpg」排序在「10.jpg, 11.jpg」後面,
因此我們會很常用到 “{:0>8d}” 補上空缺,
變成 01.jpg, 02.jpg 解決檔案自動排序問題。

另外,此功能預設就是向右對齊,所以有時候我們也會省略,寫成 “{:08d}”

數字格式化

"{:.2f}".format(2.0) # 小數點後留下2位

常用功能:我們想讓小數點後面留下幾位數,就會寫成 “{:.3f}”
(小數點後留三位數的意思)

Reference

https://blog.jaycetyle.com/2018/01/python-format-string/
https://www.runoob.com/python/att-string-format.html

⭐Python 基礎用法 相關文章整理⭐:
1.【Python】python list 清除, 移除內容元素 remove, pop, del, clear相關用法整理 sample code (內含範例程式碼)
2.【Python】寫模組 module、package 總整理 Importing files from different folder
3.【Python】python assert (斷言) 用法 sample code (內含範例程式碼)
4.【Python】python 一行 if else 語法 (one line if else) sample code (內含範例程式碼)
5.【Python】lambda 與 def function 使用方法與比較整理(內含範例程式碼)
6.【Python】python map 使用方法 與 其他寫法比較整理 (內含範例程式碼) sample code
7.【Python】python zip 使用方法 與 其他寫法比較整理 (內含範例程式碼) sample code
⭐Python 字串處理 相關文章整理⭐:
1.【Python】python print 變數的值 & 變數名稱 方法總整理
2.【Python】python string format str.format 總整理
⭐Python 檔案處理 相關文章整理⭐:
1.【Python】python 開關檔範例 與 程式模板 with open / file open sample code
2.【Python】取出檔案名稱 (含副檔名、不含副檔名) os path basename split 取出 檔名 路徑 不要副檔名 sample code
3.【Python】在 python 中利用 os.chmod 更改檔案的權限 chmod 777
4.【Python】利用 shutil 來複製檔案 shutil copy file
5.【Python】python 建立資料夾範例 mkdir os.makedirs() sample code
6.【Python】python 移除資料夾範例 rmdir shutil.rmtree() sample code
7.【Python】確認檔案是否存在 os.path.isfile / 確認資料夾是否存在 os.path.isdir sample code is folder / file exist
⭐Python 系統偵測 相關文章整理⭐:
1.【Python】python pyinotify sample code 偵測指定路徑底下的文件變化 (內有範例程式碼)
2.【Python】python 利用 argparse 使程式執行時可帶參數 (內附範例程式碼) sample code
⭐Python 平行運算 相關文章整理⭐:
1.【Python】threading – 建立多執行緒來執行程式 (內含範例程式碼) sample code
2.【Pytho