Lesson 04: Strings – Chuỗi

🎯 Mục Tiêu

  • Hiểu strings và cách tạo
  • String methods quan trọng
  • String formatting
  • String slicing và manipulation

Tạo Strings

# Single quotes
name = 'Python'

# Double quotes
message = "Hello, World!"

# Triple quotes (multiline)
paragraph = """Đây là chuỗi
nhiều dòng trong Python"""

# Escape characters
quote = "He said: \"Python is awesome!\""
path = "C:\\Users\\Admin"

String Indexing & Slicing

text = "Python"

# Indexing
text[0]    # 'P'
text[-1]   # 'n' (cuối cùng)

# Slicing
text[0:3]  # 'Pyt'
text[:3]   # 'Pyt'
text[3:]   # 'hon'
text[::-1] # 'nohtyP' (đảo ngược)

String Methods

text = "  Hello World  "

# Case conversion
text.lower()        # "  hello world  "
text.upper()        # "  HELLO WORLD  "
text.title()        # "  Hello World  "
text.capitalize()   # "  hello world  "

# Whitespace
text.strip()        # "Hello World"
text.lstrip()       # "Hello World  "
text.rstrip()       # "  Hello World"

# Search & Replace
text.find("World")  # 8 (index)
text.replace("World", "Python")  # "  Hello Python  "

# Split & Join
words = "a,b,c".split(",")  # ['a', 'b', 'c']
"-".join(['a', 'b', 'c'])   # "a-b-c"

# Check methods
text.startswith("Hello")  # False (có spaces)
text.endswith("World")    # False
"123".isdigit()           # True
"abc".isalpha()           # True

String Formatting

name = "An"
age = 25

# F-strings (Python 3.6+) - Khuyến nghị!
message = f"Tôi là {name}, {age} tuổi"

# Format method
message = "Tôi là {}, {} tuổi".format(name, age)
message = "Tôi là {n}, {a} tuổi".format(n=name, a=age)

# Old style (%)
message = "Tôi là %s, %d tuổi" % (name, age)

# Number formatting
pi = 3.14159
print(f"Pi: {pi:.2f}")  # "Pi: 3.14"
num = 1000000
print(f"Số: {num:,}")   # "Số: 1,000,000"

String Concatenation

# Dùng +
greeting = "Hello" + " " + "World"

# Dùng join (hiệu quả hơn với nhiều strings)
words = ["Hello", "Python", "World"]
sentence = " ".join(words)

# Repetition
print("=" * 50)  # In 50 dấu =

💡 Key Takeaways

  • Strings are immutable (không thể thay đổi)
  • Index bắt đầu từ 0
  • F-strings là cách format tốt nhất
  • Dùng .strip() để xóa whitespace
  • Triple quotes cho multiline strings

✍️ Bài tập:

BÀI 1: String Length Tạo biến name = "Nguyen Van An" In ra số ký tự trong tên

BÀI 2: Upper & Lower Cho: text = "pYtHoN pRoGrAmMiNg" .In text dưới dạng lowercase và uppercase

BÀI 3: Strip Whitespace Cho: message = "   Hello World   " Xóa khoảng trắng 2 đầu và in kết quả

BÀI 4: Replace Cho: sentence = "I love Java" Thay “Java” bằng “Python” và in ra

BÀI 5: Split String Cho: fruits = "apple,banana,cherry,mango" Split thành list và in từng fruit trên 1 dòng

BÀI 6: Join Strings. Cho: words = ["Python", "is", "awesome"]. Join thành câu với khoảng trắng và in ra

BÀI 7: String Slicing. Cho: text = "Python Programming". In ra từ “Python” (6 ký tự đầu). In ra từ “Programming” (từ ký tự thứ 7 trở đi)

BÀI 8: Reverse String Cho: word = “Hello” Đảo ngược string và in ra

BÀI 9: Count Substring Cho: text = "Python is great. I love Python. Python rocks!". Đếm xem từ “Python” xuất hiện bao nhiêu lần

BÀI 10: Check Digit
# Cho: code = "12345"
# Kiểm tra xem tất cả ký tự có phải số không
code = “12345”

# BÀI 11: F-string Formatting
# Tạo biến: name=”An”, age=25, city=”Hà Nội”
# In câu: “Tôi là An, 25 tuổi, sống ở Hà Nội”
# Dùng f-string

# BÀI 12: Email Extractor
# Cho: text = “Contact me at: user@example.com for details”
# Tìm và in ra email (giữa “at: ” và ” for”)
text = “Contact me at: user@example.com for details”

# BONUS: Password Validator
# Tạo password checker:
# – Độ dài >= 8
# – Chứa ít nhất 1 số (dùng any() và isdigit())

➡️ Bài Tiếp Theo : Lesson 05 – Input/Output

 

Leave a Reply

Your email address will not be published. Required fields are marked *