Skip to main content

Bài 12 - Kiểu dữ liệu chuỗi (string) trong Python

I. Giới Thiệu

Chuỗi (string) là kiểu dữ liệu cơ bản trong Python dùng để lưu trữ và xử lý văn bản. Đặc điểm chính:

  • Bất biến (immutable): Không thể thay đổi sau khi tạo
  • Hỗ trợ Unicode: Làm việc tốt với mọi ngôn ngữ
  • Linh hoạt: Nhiều phương thức xử lý tích hợp

# Các cách tạo chuỗi
s1 = 'Hello World'         # Nháy đơn
s2 = "Python Programming"  # Nháy kép
s3 = '''Đây là
chuỗi nhiều dòng'''        # Nháy ba
s4 = r"C:\new\folder"      # Raw string (bỏ qua ký tự đặc biệt)

II. Các Thao Tác Cơ Bản

1. Truy cập ký tự

s = "Python"
print(s[0])   # 'P' - Chỉ số dương từ trái
print(s[-1])  # 'n' - Chỉ số âm từ phải

2. Cắt hay thái chuỗi (Slicing)

s = "Hello World"
print(s[0:5])   # "Hello"  [start:end]
print(s[6:])    # "World"   [start:]
print(s[:5])    # "Hello"   [:end]
print(s[::-1])  # "dlroW olleH" - Đảo ngược

3. Nối chuỗi

name = "Alice"
greeting = "Hello, " + name + "!"  # "Hello, Alice!"

4. Lặp chuỗi

stars = "*" * 10  # "**********"

III. Phương Thức Xử Lý Chuỗi Quan Trọng

Phương thứcMô tảVí dụ
str.upper()Chuyển thành chữ hoa"hello".upper() → "HELLO"
str.lower()Chuyển thành chữ thường"HELLO".lower() → "hello"
str.strip()Xóa khoảng trắng đầu/cuối" text ".strip() → "text"
str.split()Tách chuỗi thành list"a,b,c".split(",") → ['a','b','c']
str.join()Nối các phần tử",".join(['a','b','c']) → "a,b,c"
str.replace()Thay thế chuỗi con"Hello".replace("H","J") → "Jello"
str.find()Tìm vị trí chuỗi con"Python".find("th") → 2
str.startswith()Kiểm tra bắt đầu bằng"file.txt".startswith("file") → True
str.endswith()Kiểm tra kết thúc bằng"image.png".endswith(".png") → True
str.isdigit()Kiểm tra có phải số"123".isdigit() → True

IV. Định Dạng Chuỗi (String Formatting)

1. f-strings (Python 3.6+)

name = "Alice"
age = 25
print(f"{name} is {age} years old")  # "Alice is 25 years old"

2. str.format()

print("{} is {} years old".format(name, age))

3. %-formatting (cũ)

print("%s is %d years old" % (name, age))

4. Định dạng nâng cao

pi = 3.14159
print(f"Pi: {pi:.2f}")      # "Pi: 3.14"
print(f"Hex: {255:#x}")     # "Hex: 0xff"
print(f"Percent: {0.25:%}") # "Percent: 25.000000%"

V. Xử Lý Ký Tự Đặc Biệt

Ký tựÝ nghĩaVí dụ
\nXuống dòngprint("Line1\nLine2")
\tTab ngangprint("Name:\tAlice")
\\Dấu \"C:\\folder"
\"Nháy kép"She said: \"Hello\""
\'Nháy đơn'It\'s me'

VI. Chuỗi Đa Ngôn Ngữ & Unicode

python

 

# Tiếng Việt vn_str = "Xin chào Việt Nam" print(vn_str)  # Xuất chuỗi Unicode chuẩn # Mã hóa/giải mã encoded = vn_str.encode("utf-8")  # b'Xin ch\xc3\xa0o...' decoded = encoded.decode("utf-8") # "Xin chào Việt Nam"

VII. Kiểm Tra & Xác Thực Chuỗi

# Tiếng Việt
vn_str = "Xin chào Việt Nam"
print(vn_str)  # Xuất chuỗi Unicode chuẩn

# Mã hóa/giải mã
encoded = vn_str.encode("utf-8")  # b'Xin ch\xc3\xa0o...'
decoded = encoded.decode("utf-8") # "Xin chào Việt Nam"

VIII. Ứng Dụng Thực Tế

1. Xử lý dữ liệu nhập

user_input = "  ALICE  "
clean_name = user_input.strip().title()  # "Alice"

2. Tách tên file và phần mở rộng

filename = "report_2023.xlsx"
name = filename.split(".")[0]   # "report_2023"
extension = filename.split(".")[-1]  # "xlsx"

3. Tạo template động

email_template = """
Dear {name},
Your order #{order_id} is ready.
Total: ${amount:.2f}
"""
print(email_template.format(name="Bob", order_id=123, amount=49.99))

IX. Best Practices

  1. Ưu tiên f-strings cho code rõ ràng và hiệu suất
  2. Xử lý chuỗi lớn: Dùng join thay vì nối bằng +

    # ❌ Kém hiệu quả
    result = ""
    for s in list_str:
       result += s

    # ✅ Tối ưu
    result = "".join(list_str)

  3. Sử dụng raw string cho đường dẫn và regex

    path = r"C:\new\folder\file.txt"

  4. Kiểm tra empty string

    if not my_string:  # Thay vì len(my_string) == 0
       print("Chuỗi rỗng")

X. Bài Tập Thực Hành

  1. Đảo ngược từ trong chuỗi

    def reverse_words(s):
       return " ".join(s.split()[::-1])

    print(reverse_words("Hello World"))  # "World Hello"

  2. Đếm nguyên âm

    def count_vowels(s):
       vowels = "aeiouAEIOU"
       return sum(1 for char in s if char in vowels)

  3. Kiểm tra palindrome

    def is_palindrome(s):
       clean = ''.join(filter(str.isalnum, s)).lower()
       return clean == clean[::-1]

Tài Nguyên: