フォーマット済み文字列リテラル

Pythonで学ぶ正規表現

Maria Eugenia Inzaugarat

Data Scientist

f文字列(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文字列ではバックスラッシュは不可
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...