Skip to content

📝 13.3 Bài tập string methods

📖 Giới thiệu

Bài học này tập hợp các bài tập thực hành từ cơ bản đến nâng cao về string methods. Thông qua việc giải quyết các bài toán thực tế, bạn sẽ nắm vững cách sử dụng các phương thức xử lý chuỗi trong Python.

INFO

Thực hành nhiều sẽ giúp bạn sử dụng string methods một cách tự nhiên và hiệu quả

🎓 Bài tập giáo dục

🔤 Bài 1: Chuẩn hóa tên học sinh

python
def chuan_hoa_ten(ten_khong_chuan):
    """
    Chuẩn hóa tên học sinh: 
    - Loại bỏ khoảng trắng thừa
    - Viết hoa chữ cái đầu mỗi từ
    - Loại bỏ ký tự đặc biệt
    """
    # Loại bỏ khoảng trắng đầu cuối
    ten = ten_khong_chuan.strip()
    
    # Loại bỏ ký tự số và đặc biệt (giữ lại chữ cái và khoảng trắng)
    ten_sach = ""
    for char in ten:
        if char.isalpha() or char.isspace():
            ten_sach += char
    
    # Chuẩn hóa khoảng trắng (loại bỏ khoảng trắng thừa giữa các từ)
    cac_tu = ten_sach.split()
    
    # Viết hoa chữ cái đầu mỗi từ
    cac_tu_chuan = [tu.capitalize() for tu in cac_tu]
    
    return " ".join(cac_tu_chuan)

# Test với các tên không chuẩn
danh_sach_ten_loi = [
    "  nguyễn    văn   an  ",
    "TRẦN THỊ   bình123",
    "lê-văn*chi",
    "phạm thị DUNG  ",
    "hoàng  VĂN  em"
]

print("🎓 CHUẨN HÓA TÊN HỌC SINH")
print("="*50)

for ten_loi in danh_sach_ten_loi:
    ten_chuan = chuan_hoa_ten(ten_loi)
    print(f"'{ten_loi}' → '{ten_chuan}'")

# Ứng dụng: Xử lý danh sách lớp
def xu_ly_danh_sach_lop(file_content):
    """Xử lý danh sách học sinh từ file text"""
    dong_du_lieu = file_content.strip().split("\n")
    danh_sach_chuan = []
    
    for i, dong in enumerate(dong_du_lieu, 1):
        if dong.strip():  # Bỏ qua dòng trống
            ten_chuan = chuan_hoa_ten(dong)
            danh_sach_chuan.append(f"{i:02d}. {ten_chuan}")
    
    return danh_sach_chuan

# Mô phỏng dữ liệu từ file
du_lieu_lop = """
  nguyễn văn an  
TRẦN THỊ bình
lê văn chi123
phạm thị dung  
hoàng văn em
"""

danh_sach_chuan = xu_ly_danh_sach_lop(du_lieu_lop)
print(f"\n📚 DANH SÁCH LỚP ĐÃ CHUẨN HÓA:")
for hoc_sinh in danh_sach_chuan:
    print(f"  {hoc_sinh}")

TIP

Luôn chuẩn hóa dữ liệu đầu vào để tránh lỗi xử lý về sau

📊 Bài 2: Phân tích bài văn

python
def phan_tich_van_ban(noi_dung):
    """Phân tích chi tiết một đoạn văn bản"""
    
    # Thống kê cơ bản
    so_ky_tu = len(noi_dung)
    so_ky_tu_khong_khoang_trang = len(noi_dung.replace(" ", ""))
    so_tu = len(noi_dung.split())
    so_cau = noi_dung.count(".") + noi_dung.count("!") + noi_dung.count("?")
    so_doan = noi_dung.count("\n\n") + 1
    
    print("📊 PHÂN TÍCH VĂN BẢN")
    print("="*40)
    print(f"📏 Tổng ký tự: {so_ky_tu}")
    print(f"🔤 Ký tự (không space): {so_ky_tu_khong_khoang_trang}")
    print(f"📝 Số từ: {so_tu}")
    print(f"💬 Số câu: {so_cau}")
    print(f"📄 Số đoạn: {so_doan}")
    
    # Phân tích từ vựng
    cac_tu = noi_dung.lower().split()
    
    # Loại bỏ dấu câu và đếm từ
    tu_sach = []
    for tu in cac_tu:
        tu_clean = ""
        for char in tu:
            if char.isalpha():
                tu_clean += char
        if tu_clean:
            tu_sach.append(tu_clean)
    
    # Đếm tần suất từ
    dem_tu = {}
    for tu in tu_sach:
        dem_tu[tu] = dem_tu.get(tu, 0) + 1
    
    # Tìm từ phổ biến nhất
    tu_pho_bien = sorted(dem_tu.items(), key=lambda x: x[1], reverse=True)
    
    print(f"\n🔥 TOP 5 TỪ PHỔ BIẾN:")
    for tu, so_lan in tu_pho_bien[:5]:
        print(f"  '{tu}': {so_lan} lần")
    
    # Phân tích độ dài từ
    do_dai_tu = [len(tu) for tu in tu_sach]
    do_dai_tb = sum(do_dai_tu) / len(do_dai_tu) if do_dai_tu else 0
    tu_dai_nhat = max(tu_sach, key=len) if tu_sach else ""
    
    print(f"\n📐 PHÂN TÍCH ĐỘ DÀI:")
    print(f"  Độ dài TB: {do_dai_tb:.1f} ký tự")
    print(f"  Từ dài nhất: '{tu_dai_nhat}' ({len(tu_dai_nhat)} ký tự)")
    
    # Tính mức độ đọc
    if so_cau > 0:
        tb_tu_moi_cau = so_tu / so_cau
        if tb_tu_moi_cau < 10:
            muc_do = "Dễ đọc"
        elif tb_tu_moi_cau < 20:
            muc_do = "Trung bình"
        else:
            muc_do = "Khó đọc"
        
        print(f"\n📖 ĐÁNH GIÁ:")
        print(f"  TB từ/câu: {tb_tu_moi_cau:.1f}")
        print(f"  Mức độ: {muc_do}")

# Test với đoạn văn mẫu
van_ban_mau = """
Python là một ngôn ngữ lập trình mạnh mẽ và dễ học. 
Với cú pháp đơn giản và rõ ràng, Python giúp lập trình viên 
tập trung vào giải quyết vấn đề thay vì lo lắng về cú pháp phức tạp.

Python được sử dụng rộng rãi trong nhiều lĩnh vực như 
phát triển web, khoa học dữ liệu, trí tuệ nhân tạo và tự động hóa. 
Cộng đồng Python rất lớn và luôn sẵn sàng hỗ trợ người mới học.
"""

phan_tich_van_ban(van_ban_mau)

💼 Bài tập kinh doanh

📞 Bài 3: Xử lý thông tin liên hệ

python
class XuLyThongTinLienHe:
    def __init__(self):
        self.danh_ba = []
    
    def chuan_hoa_sdt(self, sdt):
        """Chuẩn hóa số điện thoại về format 0xxxxxxxxx"""
        # Loại bỏ tất cả ký tự không phải số
        so_clean = ""
        for char in sdt:
            if char.isdigit():
                so_clean += char
        
        # Xử lý các trường hợp khác nhau
        if so_clean.startswith("84"):  # Số có mã vùng +84
            so_clean = "0" + so_clean[2:]
        elif len(so_clean) == 9:  # Số thiếu số 0 đầu
            so_clean = "0" + so_clean
        
        # Kiểm tra độ dài hợp lệ
        if len(so_clean) == 10 and so_clean.startswith("0"):
            return so_clean
        else:
            return None
    
    def kiem_tra_email(self, email):
        """Kiểm tra email hợp lệ (đơn giản)"""
        email = email.strip().lower()
        
        # Kiểm tra cơ bản
        if "@" not in email or email.count("@") != 1:
            return False, "Email phải có đúng 1 ký tự @"
        
        local, domain = email.split("@")
        
        if not local or not domain:
            return False, "Email không được có phần rỗng"
        
        if "." not in domain:
            return False, "Domain phải có ít nhất 1 dấu chấm"
        
        # Kiểm tra ký tự hợp lệ
        hop_le_chars = set("abcdefghijklmnopqrstuvwxyz0123456789.-_")
        for char in email:
            if char not in hop_le_chars and char != "@":
                return False, f"Ký tự '{char}' không hợp lệ"
        
        return True, "Email hợp lệ"
    
    def them_lien_he(self, ten, sdt, email):
        """Thêm liên hệ mới sau khi validate"""
        ten_chuan = ten.strip().title()
        
        # Validate và chuẩn hóa SĐT
        sdt_chuan = self.chuan_hoa_sdt(sdt)
        if not sdt_chuan:
            return False, f"SĐT không hợp lệ: {sdt}"
        
        # Validate email
        email_hop_le, thong_bao = self.kiem_tra_email(email)
        if not email_hop_le:
            return False, f"Email lỗi: {thong_bao}"
        
        # Kiểm tra trùng lặp
        for lien_he in self.danh_ba:
            if lien_he["sdt"] == sdt_chuan:
                return False, f"SĐT {sdt_chuan} đã tồn tại"
            if lien_he["email"] == email.lower():
                return False, f"Email {email} đã tồn tại"
        
        # Thêm vào danh bạ
        self.danh_ba.append({
            "ten": ten_chuan,
            "sdt": sdt_chuan,
            "email": email.lower().strip()
        })
        
        return True, "Thêm liên hệ thành công"
    
    def tim_kiem(self, tu_khoa):
        """Tìm kiếm liên hệ theo tên, SĐT hoặc email"""
        tu_khoa_lower = tu_khoa.lower()
        ket_qua = []
        
        for lien_he in self.danh_ba:
            if (tu_khoa_lower in lien_he["ten"].lower() or
                tu_khoa in lien_he["sdt"] or
                tu_khoa_lower in lien_he["email"]):
                ket_qua.append(lien_he)
        
        return ket_qua
    
    def in_danh_ba(self):
        """In toàn bộ danh bạ"""
        if not self.danh_ba:
            print("📞 Danh bạ trống")
            return
        
        print("📞 DANH BẠ LIÊN HỆ")
        print("="*60)
        for i, lh in enumerate(self.danh_ba, 1):
            print(f"{i:2d}. {lh['ten']:<20} | {lh['sdt']} | {lh['email']}")

# Test hệ thống
xl = XuLyThongTinLienHe()

# Dữ liệu test (có lỗi)
du_lieu_test = [
    ("nguyễn văn an", "0901-234-567", "an@gmail.com"),
    ("trần thị bình", "84905123456", "binh.tran@company.vn"),
    ("lê văn chi", "905-123-4567", "chi_le@hotmail.com"),
    ("phạm thị dung", "0901234567", "invalid.email"),  # Email lỗi
    ("hoàng văn em", "123456789", "em@domain.com"),   # SĐT thiếu số 0
]

print("💼 THÊM LIÊN HỆ VÀO DANH BẠ")
print("="*50)

for ten, sdt, email in du_lieu_test:
    thanh_cong, thong_bao = xl.them_lien_he(ten, sdt, email)
    status = "✅" if thanh_cong else "❌"
    print(f"{status} {ten}: {thong_bao}")

print()
xl.in_danh_ba()

# Test tìm kiếm
print(f"\n🔍 Tìm 'an':")
ket_qua = xl.tim_kiem("an")
for lh in ket_qua:
    print(f"  • {lh['ten']} - {lh['sdt']}")

WARNING

Validation dữ liệu là bước quan trọng để đảm bảo chất lượng hệ thống

💳 Bài 4: Validate thông tin thanh toán

python
def kiem_tra_so_the_tin_dung(so_the):
    """
    Kiểm tra số thẻ tín dụng bằng thuật toán Luhn (đơn giản hóa)
    """
    # Loại bỏ khoảng trắng và dấu gạch ngang
    so_sach = so_the.replace(" ", "").replace("-", "")
    
    # Kiểm tra chỉ chứa số
    if not so_sach.isdigit():
        return False, "Số thẻ chỉ được chứa số"
    
    # Kiểm tra độ dài
    if len(so_sach) < 13 or len(so_sach) > 19:
        return False, "Số thẻ phải có 13-19 chữ số"
    
    # Xác định loại thẻ dựa trên số đầu
    if so_sach.startswith("4"):
        loai_the = "Visa"
    elif so_sach.startswith("5"):
        loai_the = "MasterCard"
    elif so_sach.startswith("3"):
        loai_the = "American Express"
    else:
        loai_the = "Không xác định"
    
    # Thuật toán Luhn đơn giản (demo)
    tong = 0
    for i, chu_so in enumerate(reversed(so_sach)):
        n = int(chu_so)
        if i % 2 == 1:  # Vị trí lẻ (từ phải sang trái)
            n *= 2
            if n > 9:
                n = n // 10 + n % 10
        tong += n
    
    hop_le = tong % 10 == 0
    return hop_le, loai_the if hop_le else "Số thẻ không hợp lệ"

def kiem_tra_cvv(cvv, loai_the):
    """Kiểm tra mã CVV"""
    if not cvv.isdigit():
        return False, "CVV chỉ được chứa số"
    
    if loai_the == "American Express":
        if len(cvv) != 4:
            return False, "CVV của Amex phải có 4 chữ số"
    else:
        if len(cvv) != 3:
            return False, "CVV phải có 3 chữ số"
    
    return True, "CVV hợp lệ"

def kiem_tra_ngay_het_han(mm_yy):
    """Kiểm tra ngày hết hạn thẻ"""
    import datetime
    
    # Parse MM/YY format
    if "/" not in mm_yy or len(mm_yy.split("/")) != 2:
        return False, "Format phải là MM/YY"
    
    try:
        thang, nam = mm_yy.split("/")
        thang = int(thang)
        nam = int("20" + nam)  # Giả sử 2-digit year là 20xx
        
        if thang < 1 or thang > 12:
            return False, "Tháng phải từ 01-12"
        
        # So sánh với thời gian hiện tại
        now = datetime.datetime.now()
        ngay_het_han = datetime.date(nam, thang, 1)
        ngay_hien_tai = datetime.date(now.year, now.month, 1)
        
        if ngay_het_han < ngay_hien_tai:
            return False, "Thẻ đã hết hạn"
        
        return True, f"Hết hạn: {thang:02d}/{nam}"
        
    except ValueError:
        return False, "Tháng/năm không hợp lệ"

def validate_thong_tin_thanh_toan(so_the, cvv, ngay_het_han, ten_chu_the):
    """Validate toàn bộ thông tin thanh toán"""
    print("💳 KIỂM TRA THÔNG TIN THANH TOÁN")
    print("="*50)
    
    ket_qua = {}
    
    # Kiểm tra số thẻ
    hop_le_the, loai_the = kiem_tra_so_the_tin_dung(so_the)
    ket_qua["so_the"] = {"hop_le": hop_le_the, "thong_tin": loai_the}
    print(f"💳 Số thẻ: {'✅' if hop_le_the else '❌'} {loai_the}")
    
    # Kiểm tra CVV
    hop_le_cvv, msg_cvv = kiem_tra_cvv(cvv, loai_the if hop_le_the else "")
    ket_qua["cvv"] = {"hop_le": hop_le_cvv, "thong_tin": msg_cvv}
    print(f"🔐 CVV: {'✅' if hop_le_cvv else '❌'} {msg_cvv}")
    
    # Kiểm tra ngày hết hạn
    hop_le_ngay, msg_ngay = kiem_tra_ngay_het_han(ngay_het_han)
    ket_qua["ngay_het_han"] = {"hop_le": hop_le_ngay, "thong_tin": msg_ngay}
    print(f"📅 Hết hạn: {'✅' if hop_le_ngay else '❌'} {msg_ngay}")
    
    # Kiểm tra tên chủ thẻ
    ten_hop_le = len(ten_chu_the.strip()) >= 2 and all(c.isalpha() or c.isspace() for c in ten_chu_the)
    ket_qua["ten_chu_the"] = {"hop_le": ten_hop_le, "thong_tin": ten_chu_the.upper() if ten_hop_le else "Tên không hợp lệ"}
    print(f"👤 Tên: {'✅' if ten_hop_le else '❌'} {ket_qua['ten_chu_the']['thong_tin']}")
    
    # Kết luận
    toan_bo_hop_le = all(v["hop_le"] for v in ket_qua.values())
    print(f"\n🎯 KẾT QUẢ: {'✅ Thông tin hợp lệ' if toan_bo_hop_le else '❌ Có lỗi cần sửa'}")
    
    return ket_qua

# Test với nhiều trường hợp
test_cases = [
    ("4532 1234 5678 9012", "123", "12/25", "Nguyen Van An"),
    ("5555444433332222", "456", "03/24", "Tran Thi Binh"),  # Hết hạn
    ("378282246310005", "1234", "08/26", "Le Van Chi"),     # Amex
    ("4532-1234-5678-901", "12", "15/25", "123"),          # CVV sai, tên sai
]

for i, (so_the, cvv, ngay, ten) in enumerate(test_cases, 1):
    print(f"\n🧪 TEST CASE {i}:")
    validate_thong_tin_thanh_toan(so_the, cvv, ngay, ten)
    print()

🔍 Bài tập xử lý dữ liệu

🧹 Bài 5: Data cleaning cho database

python
class DataCleaner:
    """Lớp xử lý và làm sạch dữ liệu"""
    
    @staticmethod
    def lam_sach_ten(ten):
        """Làm sạch tên người"""
        if not ten or not isinstance(ten, str):
            return ""
        
        # Loại bỏ ký tự đặc biệt, chỉ giữ chữ cái và khoảng trắng
        ten_sach = ""
        for char in ten:
            if char.isalpha() or char.isspace():
                ten_sach += char
        
        # Chuẩn hóa khoảng trắng và viết hoa
        cac_tu = ten_sach.strip().split()
        return " ".join(tu.capitalize() for tu in cac_tu if tu)
    
    @staticmethod
    def lam_sach_email(email):
        """Làm sạch và validate email"""
        if not email or not isinstance(email, str):
            return ""
        
        email = email.strip().lower()
        
        # Kiểm tra format cơ bản
        if "@" not in email or email.count("@") != 1:
            return ""
        
        local, domain = email.split("@")
        if not local or not domain or "." not in domain:
            return ""
        
        return email
    
    @staticmethod
    def lam_sach_so_dien_thoai(sdt):
        """Chuẩn hóa số điện thoại"""
        if not sdt:
            return ""
        
        # Chỉ giữ lại số
        so_clean = "".join(char for char in str(sdt) if char.isdigit())
        
        # Chuẩn hóa về format VN
        if len(so_clean) == 9:
            so_clean = "0" + so_clean
        elif len(so_clean) == 11 and so_clean.startswith("84"):
            so_clean = "0" + so_clean[2:]
        
        # Kiểm tra độ dài hợp lệ
        if len(so_clean) == 10 and so_clean.startswith("0"):
            return so_clean
        
        return ""
    
    @staticmethod
    def xu_ly_du_lieu_csv(csv_content):
        """Xử lý dữ liệu từ CSV và trả về dữ liệu đã làm sạch"""
        lines = csv_content.strip().split("\n")
        
        # Phân tích header
        header = lines[0].split(",")
        print(f"📋 Columns: {header}")
        
        du_lieu_sach = []
        loi_count = 0
        
        for i, line in enumerate(lines[1:], 2):  # Bỏ header
            fields = line.split(",")
            
            if len(fields) != len(header):
                print(f"❌ Dòng {i}: Sai số cột")
                loi_count += 1
                continue
            
            # Tạo dict cho từng record
            record = {}
            hop_le = True
            
            for j, (col, value) in enumerate(zip(header, fields)):
                col = col.strip().lower()
                
                if "name" in col or "ten" in col:
                    clean_value = DataCleaner.lam_sach_ten(value)
                elif "email" in col:
                    clean_value = DataCleaner.lam_sach_email(value)
                elif "phone" in col or "sdt" in col:
                    clean_value = DataCleaner.lam_sach_so_dien_thoai(value)
                else:
                    clean_value = value.strip()
                
                # Kiểm tra bắt buộc (giả sử tên và email bắt buộc)
                if ("name" in col or "ten" in col or "email" in col) and not clean_value:
                    print(f"❌ Dòng {i}: {col} bị trống hoặc không hợp lệ")
                    hop_le = False
                    break
                
                record[col] = clean_value
            
            if hop_le:
                du_lieu_sach.append(record)
            else:
                loi_count += 1
        
        print(f"\n📊 KẾT QUẢ XỬ LÝ:")
        print(f"  ✅ Thành công: {len(du_lieu_sach)} records")
        print(f"  ❌ Lỗi: {loi_count} records")
        
        return du_lieu_sach

# Test với dữ liệu CSV có lỗi
csv_data = """name,email,phone,age
  nguyễn văn an  ,an@gmail.com,0901234567,25
TRAN thi binh,binh.tran@company.vn,84905123456,30
le van chi,invalid.email,905123456,28
,empty@name.com,0903456789,22
pham thi dung,dung@domain.com,,35
hoang van em,em@test.com,0907654321,27"""

print("🧹 DATA CLEANING DEMO")
print("="*50)

cleaned_data = DataCleaner.xu_ly_du_lieu_csv(csv_data)

print(f"\n📋 DỮ LIỆU ĐÃ LÀM SẠCH:")
for record in cleaned_data:
    print(f"  • {record}")

🎮 Bài tập game và giải trí

🎯 Bài 6: Game đoán từ

python
import random

class GameDoanTu:
    def __init__(self):
        self.tu_vung = [
            "python", "programming", "computer", "algorithm", 
            "database", "internet", "software", "hardware",
            "developer", "website", "security", "network"
        ]
        self.tu_hien_tai = ""
        self.tu_da_doan = set()
        self.so_lan_sai = 0
        self.max_sai = 6
    
    def bat_dau_game_moi(self):
        """Bắt đầu game mới"""
        self.tu_hien_tai = random.choice(self.tu_vung).upper()
        self.tu_da_doan = set()
        self.so_lan_sai = 0
        print("🎯 GAME ĐOÁN TỪ")
        print("="*30)
        print(f"Từ có {len(self.tu_hien_tai)} ký tự")
        print(f"Bạn có {self.max_sai} lần đoán sai")
    
    def hien_thi_trang_thai(self):
        """Hiển thị trạng thái hiện tại"""
        # Hiển thị từ với các ký tự đã đoán
        tu_hien_thi = ""
        for ky_tu in self.tu_hien_tai:
            if ky_tu in self.tu_da_doan:
                tu_hien_thi += ky_tu + " "
            else:
                tu_hien_thi += "_ "
        
        print(f"\n📝 Từ: {tu_hien_thi}")
        print(f"🔤 Đã đoán: {sorted(self.tu_da_doan)}")
        print(f"❌ Sai: {self.so_lan_sai}/{self.max_sai}")
        
        # Vẽ hình người treo cổ đơn giản
        hinh_nguoi = [
            "   +---+",
            "   |   |",
            "   O   |" if self.so_lan_sai >= 1 else "       |",
            "  /|\\  |" if self.so_lan_sai >= 3 else "  /|   |" if self.so_lan_sai >= 2 else "   |   |" if self.so_lan_sai >= 1 else "       |",
            "  / \\  |" if self.so_lan_sai >= 5 else "  /    |" if self.so_lan_sai >= 4 else "       |",
            "       |",
            "=========",
        ]
        
        for dong in hinh_nguoi:
            print(dong)
    
    def doan_ky_tu(self, ky_tu):
        """Xử lý việc đoán một ký tự"""
        ky_tu = ky_tu.upper()
        
        if not ky_tu.isalpha() or len(ky_tu) != 1:
            return "❌ Vui lòng nhập một ký tự từ A-Z"
        
        if ky_tu in self.tu_da_doan:
            return f"⚠️ Bạn đã đoán '{ky_tu}' rồi"
        
        self.tu_da_doan.add(ky_tu)
        
        if ky_tu in self.tu_hien_tai:
            # Kiểm tra thắng
            if all(c in self.tu_da_doan for c in self.tu_hien_tai):
                return "🎉 CHÚC MỪNG! Bạn đã đoán đúng từ!"
            else:
                return f"✅ Đúng! Ký tự '{ky_tu}' có trong từ"
        else:
            self.so_lan_sai += 1
            if self.so_lan_sai >= self.max_sai:
                return f"💀 GAME OVER! Từ đúng là: {self.tu_hien_tai}"
            else:
                return f"❌ Sai! Ký tự '{ky_tu}' không có trong từ"
    
    def goi_y(self):
        """Đưa ra gợi ý"""
        chua_doan = [c for c in self.tu_hien_tai if c not in self.tu_da_doan]
        if chua_doan:
            ky_tu_goi_y = random.choice(chua_doan)
            return f"💡 Gợi ý: Từ có chứa ký tự '{ky_tu_goi_y}'"
        return "🤔 Không có gợi ý nào thêm"
    
    def da_ket_thuc(self):
        """Kiểm tra game đã kết thúc chưa"""
        return (self.so_lan_sai >= self.max_sai or 
                all(c in self.tu_da_doan for c in self.tu_hien_tai))

# Demo game
def choi_game():
    game = GameDoanTu()
    game.bat_dau_game_moi()
    
    # Mô phỏng một số lượt chơi
    cac_luot_choi = ["P", "R", "O", "G", "X", "A", "M", "Z", "I", "N"]
    
    for luot, ky_tu in enumerate(cac_luot_choi, 1):
        print(f"\n🎮 LƯỢT {luot}: Đoán '{ky_tu}'")
        ket_qua = game.doan_ky_tu(ky_tu)
        print(ket_qua)
        
        game.hien_thi_trang_thai()
        
        if game.da_ket_thuc():
            break
        
        # Thỉnh thoảng đưa gợi ý
        if luot % 3 == 0:
            print(game.goi_y())

# Chạy demo
choi_game()
Bài tập tự luyện

Bài 1: Text Editor đơn giản

  • Thực hiện find/replace trong văn bản
  • Đếm từ, ký tự, dòng
  • Auto-correct typos cơ bản

Bài 2: URL Validator

  • Kiểm tra URL hợp lệ
  • Tách domain, path, parameters
  • Detect protocol (http/https)

Bài 3: Password Generator & Checker

  • Tạo password mạnh
  • Kiểm tra độ mạnh password
  • Suggest improvements

Bài 4: Log File Analyzer

  • Parse log entries
  • Extract IP, timestamp, status code
  • Generate statistics report

Bài 5: Simple Chatbot

  • Pattern matching với user input
  • Canned responses
  • Basic sentiment analysis

📚 Tóm tắt

Kỹ năng đã luyện tập:

  • ✅ Validation và cleaning dữ liệu
  • ✅ Pattern matching và tìm kiếm
  • ✅ Text formatting và presentation
  • ✅ Error handling với string operations
  • ✅ Regular expressions cơ bản (không dùng re module)

Ứng dụng thực tế:

  • 🎓 Xử lý dữ liệu giáo dục (tên, điểm số)
  • 💼 Validate thông tin kinh doanh (liên hệ, thanh toán)
  • 🔍 Data cleaning cho database
  • 🎮 Game và ứng dụng giải trí

Best practices:

  • 🛡️ Luôn validate input trước khi xử lý
  • 🧹 Chuẩn hóa dữ liệu để nhất quán
  • 📊 Sử dụng string methods phù hợp cho từng task
  • 🔄 Kết hợp nhiều phương thức để xử lý phức tạp

Lời khuyên cuối

String methods là nền tảng quan trọng cho data processing. Thực hành nhiều với dữ liệu thực tế sẽ giúp bạn thành thạo và ứng dụng hiệu quả!

🐍 Khóa học Python căn bản bằng tiếng Việt