格式化字串常值

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

f-strings

  • 語法精簡
  • 在字串前加上前綴 f

way = "code"
method = "learning Python faster"
print(f"Practicing how to {way} is the best method for {method}")
Practicing how to code is the best method for learning Python faster
Python 中的正規表示法

型別轉換

  • 可用轉換:
    • !s(字串版)
    • !r(可列印表示的字串,含引號)
    • !a(同 !r,但跳脫非 ASCII 字元)

 

name = "Python"

print(f"Python is called {name!r} due to a comedy series")
Python is called 'Python' due to a comedy series
Python 中的正規表示法

格式化指定

  • 標準格式化指定:
    • e(科學記號,例如 5 10^3)
    • d(整數,例如 4)
    • f(浮點數,例如 4.5353)

 

number = 90.41890417471841

print(f"In the last 2 years, {number:.2f}% of the data was produced worldwide!")
In the last 2 years, 90.42% of the data was produced worldwide!
Python 中的正規表示法

格式化指定

 

  • datetime

 

from datetime import datetime
my_today = datetime.now()
print(f"Today's date is {my_today:%B %d, %Y}")
Today's date is April 14, 2019
Python 中的正規表示法

索引查詢

family = {"dad": "John", "siblings": "Peter"}
print("Is your dad called {family[dad]}?".format(family=family))
Is your dad called John?

 

  • 使用引號進行索引查詢:family["dad"]
print(f"Is your dad called {family[dad]}?")
NameError: name 'dad' is not defined
Python 中的正規表示法

跳脫序列

  • 跳脫序列:反斜線 \
print("My dad is called "John"")
SyntaxError: invalid syntax

 

my_string = "My dad is called \"John\""
My dad is called "John"
Python 中的正規表示法

跳脫序列

family = {"dad": "John", "siblings": "Peter"}
  • f-strings 中不允許使用反斜線
print(f"Is your dad called {family[\"dad\"]}?")
SyntaxError: f-string expression part cannot include a backslash

 

print(f"Is your dad called {family['dad']}?")
Is your dad called John?
Python 中的正規表示法

行內運算

  • 優點:可就地評估運算與呼叫函式
my_number = 4
my_multiplier = 7
print(f'{my_number} multiplied by {my_multiplier} is {my_number * my_multiplier}')
4 multiplied by 7 is 28
Python 中的正規表示法

呼叫函式

def my_function(a, b):
  return a + b
print(f"If you sum up 10 and 20 the result is {my_function(10, 20)}")
If you sum up 10 and 20 the result is 30
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...