位置格式化

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data scientist

什麼是字串格式化?

  • 字串插值

  • 在預先定義的文字中插入自訂字串或變數:

custom_string = "String formatting"
print(f"{custom_string} is a powerful technique")
String formatting is a powerful technique
  • 用途:
    • 圖表標題
    • 顯示訊息或錯誤
    • 將字串傳入函式
Python 中的正規表示法

格式化的方法

  • 位置格式化
  • 格式化字串常值
  • 範本方法
Python 中的正規表示法

位置格式化

  • 以值取代佔位符

  • str.format()

 

print("Machine learning provides {} the ability to learn {}".format("systems", "automatically"))
Machine learning provides systems the ability to learn automatically
Python 中的正規表示法

位置格式化

  • 初始字串與傳入方法的值都可用變數表示
my_string = "{} rely on {} datasets"
method = "Supervised algorithms"
condition = "labeled"
print(my_string.format(method, condition))
Supervised algorithms rely on labeled datasets
Python 中的正規表示法

重新排序值

  • 在佔位符中加入索引可重新排序值
print("{} has a friend called {} and a sister called {}".format("Betty", "Linda", "Daisy"))
Betty has a friend called Linda and a sister called Daisy

 

print("{2} has a friend called {0} and a sister called {1}".format("Betty", "Linda", "Daisy"))
Daisy has a friend called Betty and a sister called Linda
Python 中的正規表示法

具名佔位符

  • 為佔位符指定名稱
tool="Unsupervised algorithms"
goal="patterns"
print("{title} try to find {aim} in the dataset".format(title=tool, aim=goal))
Unsupervised algorithms try to find patterns in the dataset
Python 中的正規表示法

具名佔位符

my_methods = {"tool": "Unsupervised algorithms", "goal": "patterns"}
print('{data[tool]} try to find {data[goal]} in the dataset'.format(data=my_methods))
Unsupervised algorithms try to find patterns in the dataset
Python 中的正規表示法

格式規範符

  • 指定要使用的資料型別:{index:specifier}
print("Only {0:f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))
Only 0.515568% of the data produced worldwide is analyzed!

 

print("Only {0:.2f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))
Only 0.52% of the data produced worldwide is analyzed!
Python 中的正規表示法

格式化日期時間

 

from datetime import datetime
print(datetime.now())
datetime.datetime(2019, 4, 11, 20, 19, 22, 58582)

 

print("Today's date is {:%Y-%m-%d %H:%M}".format(datetime.now()))
Today's date is 2019-04-11 20:20
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...