Formatted string literal

Regular Expressions ใน 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
Regular Expressions ใน Python

การแปลงชนิดข้อมูล

  • การแปลงชนิดที่รองรับ:
    • !s (แปลงเป็น string)
    • !r (string ที่มีเครื่องหมายคำพูด)
    • !a (เหมือน !r แต่ escape อักขระที่ไม่ใช่ ASCII)

 

name = "Python"

print(f"Python is called {name!r} due to a comedy series")
Python is called 'Python' due to a comedy series
Regular Expressions ใน 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!
Regular Expressions ใน 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
Regular Expressions ใน Python

การค้นหา index

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

 

  • ใช้เครื่องหมายคำพูดสำหรับการค้นหา index: family["dad"]
print(f"Is your dad called {family[dad]}?")
NameError: name 'dad' is not defined
Regular Expressions ใน Python

Escape sequences

  • Escape sequences: แบ็กสแลช \
print("My dad is called "John"")
SyntaxError: invalid syntax

 

my_string = "My dad is called \"John\""
My dad is called "John"
Regular Expressions ใน Python

Escape sequences

family = {"dad": "John", "siblings": "Peter"}
  • ไม่อนุญาตให้ใช้แบ็กสแลชใน f-string
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?
Regular Expressions ใน Python

การดำเนินการแบบ inline

  • ข้อดี: ประมวลผลนิพจน์และเรียกใช้ฟังก์ชันแบบ inline ได้
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
Regular Expressions ใน 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
Regular Expressions ใน Python

มาฝึกกันเถอะ!

Regular Expressions ใน Python

Preparing Video For Download...