You are on page 1of 21

Bài 06 Tìm hiểu về String – Date&Time -

Math - JSON - Regex và Handling Error

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 1
MỤC TIÊU
• String trong Python

• Date & time trong Python

• Math trong Python

• JSON trong Python

• Regular Expression trong Python

• Error Handling

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 2
String trong Python
• String là kiểu dữ liệu phổ biến trong Python, chúng ta có thể tạo ra như sau
# Tạo chuỗi dùng cặp nháy ''
st1='Python Programming'
# Tạo chuỗi dùng cặp nháy ""
st2="Python is very hot!"
# truy cập các giá trị trong chuỗi
print (st1[0]) # lấy ký tự đầu tiên
print(st1[2:6]) # lấy từ ký tự 2 đến ký tự 6
print(st1[:6]) # lấy từ 0 đến 6
# nối chuối
st=st1+st2
print(st)
st=st1+st2[0:6]+'!!!'
print (st)

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 3
String trong Python
• Một số toán tử thương dùng với chuỗi
Toán tử Mô tả
+ Nối 2 chuỗi với nhau
* Nhân chuỗi thành nhiều lần
[] Lấy ra ký tự trong chuỗi
[:] Lấy ra các ký tự trong đoạn
in Trả về true nếu tồn tại ký tự trong chuỗi
not in Trả về true nếu không tồn tại ký tự trong chuỗi
% Định dạng chuỗi

# toán tử nhân
print (st*2)
# định dạng chuỗi
name="Lại Đức Chung"
age=40
print("Bạn %s năm nay %d tuổi" % (name, age))

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 4
String trong Python
• Một số phương thức của String
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
isdigit() Returns True if all characters in the string are digits
format() Formats specified values in a string
rfind() Searches the string for a specified value and returns the last position of where it was found
find() Searches the string for a specified value and returns the position of where it was found
rsplit() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
split() Splits the string at the specified separator, and returns a list
replace() Returns a string where a specified value is replaced with a specified value
join() Joins the elements of an iterable to the end of the string

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 5
String trong Python
• Một số phương thức của String

#----------Ví dụ về chuỗi----------- # format chuỗi


caption='một số phương thức của chuỗi' message = "For only {price:.2f} dollars!"
# viết hoa ký tự đầu của chuỗi print(message.format(price = 49.6))
print(caption.capitalize()) # kiểm tra chuỗi có là số không
# chuyển chuỗi về chữ thường print("1234".isdigit())
print(caption.casefold()) # tách chuỗi với khoảng trắng thành 1 list
# đếm số lần xuất hiện của 1 từ trong chuỗi print(caption.split())
print(caption.count("ch")) # tách chuỗi với ký tự xuống dòng thành 1 list
# sinh ra 1 chuỗi có độ dài xác định và đặt chuỗ str="Thank you for the music\nWelcome to the jungle"
i vào giữa các ký tự print(str.splitlines())
print(caption.center(50,"-")) # thay thế chuỗi
str1 = "I like bananas, because bananas very good"
print(str1.replace("bananas", "apples"))

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 6
Date & time trong Python
• Date & time không phải một kiểu dữ liệu trong Python, tuy nhiên bạn có thể import
module “datetime” vào để sử dụng.
import datetime # tạo đối tượng date với các thông số cụ thể
# lấy ngày giờ hiện tại của hệ thống birthday=datetime.date(1980,11,26)
now=datetime.datetime.now() print(birthday)
print(now) # định dạng ngày tháng
# lấy từng thành phần năm, tháng, ngày... print(birthday.strftime("%d/%m/%Y"))
print(now.year) print(birthday.strftime("%c"))
print(now.month) # tăng giảm thời gian sử dụng timedelta
print(now.day) print(now+datetime.timedelta(days=5))
print(now.hour) print(now-datetime.timedelta(minutes=2))
print(now.minute)
print(now.second)

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 7
Math trong Python
• Python cung cấpmột loạt các hàm toán học cơ bản được viết sẵn trong module Math.
import math
# một số hàm trong module math
print(math.sqrt(9))
print(math.pow(9,2))
print(math.ceil(9.1))
print(math.floor(9.9))
print(math.pi)
print(math.cos(0))
print(math.degrees(1))

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 8
JSON trong Python
• Python cung cấp một gói có tên json để làm việc với dữ liệu JSON
import json # chuyển thành chuỗi
# tạo chuỗi json sproduct=json.dumps(product)
person = '{ "name":"Lại Đức Chung", "age":40, "c print(sproduct)
ity":"Phủ Lý"}' # dumps các dữ liệu khác
# phân tích chuỗi print(json.dumps(["apple", "bananas"]))
jperson = json.loads(person) print(json.dumps(("apple", "bananas")))
# truy xuất thông tin print(json.dumps("hello"))
print(jperson["city"]) print(json.dumps(42))
# tạo đỗi tượng json print(json.dumps(31.76))
product={ print(json.dumps(True))
"id":"S0023","name":"Samsung Note 20 Ultra", print(json.dumps(False))
"price":23500000 print(json.dumps(None))
}

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 9
Regular Expression trong Python
• Regular Expression là một chuỗi các ký tự tạo thành mẫu tìm kiếm, để sử dụng bạn
cần import module re vào.

• Một số hàm Regex

Function Description
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 10
Regular Expression trong Python
• Metacharacters
Character Description Example
[] A set of characters "[a-m]"
\ Signals a special sequence (can also be used to escape special characters) "\d"
. Any character (except newline character) "he..o"
^ Starts with "^hello"
$ Ends with "world$"
* Zero or more occurrences "aix*"
+ One or more occurrences "aix+"
{} Exactly the specified number of occurrences "al{2}"
| Either or "falls|stays"
() Capture and group

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 11
Regular Expression trong Python
• Special Sequences
Character Description Example
\A Returns a match if the specified characters are at the beginning of the string "\AThe"
\b Returns a match where the specified characters are at the beginning or at the end of a word r"\bain"
(the "r" in the beginning is making sure that the string is being treated as a "raw string") r"ain\b"

\B Returns a match where the specified characters are present, but NOT at the beginning (or at r"\Bain"
the end) of a word r"ain\B"
(the "r" in the beginning is making sure that the string is being treated as a "raw string")
\d Returns a match where the string contains digits (numbers from 0-9) "\d"
\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space character "\s"
\S Returns a match where the string DOES NOT contain a white space character "\S"
\w Returns a match where the string contains any word characters (characters from a to Z, digits "\w"
from 0-9, and the underscore _ character)
\W Returns a match where the string DOES NOT contain any word characters "\W"
\Z Returns a match if the specified characters are at the end of the string "Spain\Z"

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 12
Regular Expression trong Python
import re
# kiểm tra xem có tìm thấy mẫu trong chuỗi không
msg="The rain in Spain"
pattern="^The.*Spain$"
if(re.search(pattern,msg)):
print('Yes, we have a match')
else:
print('No match')
# Tìm các chuỗi số có từ 8-10 số và trả về 1 list
person='Họ và tên: Lại Đức Chung\nĐiện thoại:09680181
61\nThẻ căn cước: 168024641'
number=re.findall("\\d{8,10}",person)
print(number)

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 13
Handling Error
• Ngoại lệ có thể là bất kỳ điều kiện bất thường nào trong chương trình phá vỡ luồng thực thi chương
trình đó. Bất cứ khi nào một ngoại lệ xuất hiện, chương trình sẽ ngừng thực thi, chuyển qua quá trình
gọi và in ra lỗi đến khi nó được xử lý.

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 14
Handling Error
• Python cung cấp khối lệnh try…except…finally để điều khiển ngoại lệ

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 15
Handling Error
• Python cung cấp khối lệnh try…except…finally để điều khiển ngoại lệ

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 16
Handling Error
# nhập 2 số nguyên a và b # nhập 2 số nguyên a và b
a=int(input('Nhập số a:')) a=int(input('Nhập số a:'))
b=int(input('Nhập số b:')) b=int(input('Nhập số b:'))
# sử dụng try except để điều khiển lỗi # sử dụng try except để điều khiển lỗi
try: try:
# chia a cho b # chia a cho b
c=a/b c=a/b
print('c=',c) print('c=',c)
except Exception as e: except Exception as e:
# in thông báo lỗi # in thông báo lỗi
print('Có lỗi xảy ra:',e) print('Có lỗi xảy ra:',e)
else:
print('Không có lỗi gì cả')

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 17
Handling Error
# mở tệp tin
f = open('thovui.txt')
# điểu khiển lỗi
try:
print(f.read())
except Exception as e:
print("Lỗi đọc tệp tin: ",e)
else:
print('Đọc thành công!')
finally:
f. close()

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 18
HỎI ĐÁP

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 19
Bài 06 Tìm hiểu về String - Date&Time - Math - JSON -
20
Regex và Error Handling
238 Hoàng Quốc Việt, Bắc Từ Liêm, Hà Nội

0968.27.6996

tuyensinh@bachkhoa-aptech.edu.vn

www.bachkhoa-aptech.edu.vn

Bài 06 Tìm hiểu về String - Date&Time - Math - JSON - Regex và Error Handling 21

You might also like