12. Xử lý trên chuỗi (tiếp)
Ở bài trước, bạn đã thực hiện một số thao tác trên chuỗi, như kiểm tra chuỗi con có trong một chuỗi hay không bằng từ khóa in, not in; cắt chuỗi.
Phần này, chúng ta sẽ thực hiện thêm một số thao tác trên chuỗi.
12.1 Hiệu chỉnh chuỗi
Python cung cấp một tập hợp các phương thức (methods) có sẵn giúp bạn xử lý chuỗi một cách dễ dàng.
Chuyển thành chữ in hoa (upper case)
Phương thức upper() trả về chuỗi với tất cả các ký tự được chuyển sang chữ in hoa.
Ví dụ:
a = "Van Teo"
print(a.upper())
# Kết quả: "VAN TEO"
Chuyển thành chữ thường (lower case)
Phương thức lower() trả về chuỗi với tất cả các ký tự được chuyển sang chữ thường.
Ví dụ:
a = "Van Teo"
print(a.lower())
# Kết quả: "van teo"
Xóa khoảng trắng (remove whitespace)
Khoảng trắng dư thừa là các dấu cách ở trước và/hoặc sau nội dung văn bản. Phương thức strip() sẽ loại bỏ toàn bộ khoảng trắng dư thừa ở hai đầu chuỗi.
Ví dụ:
a = " Hello, World! "
print(a.strip())
# Kết quả: "Hello, World!"
Thay thế chuỗi (replace string)
Phương thức replace() thay thế một chuỗi con này bằng một chuỗi con khác.
Ví dụ:
a = "Hello, World!"
print(a.replace("H", "J"))
# Kết quả: "Jello, World!"
Tách chuỗi (split string)
Phương thức split() trả về một danh sách (list), trong đó các phần tử của danh sách là các chuỗi con được tách ra dựa trên ký tự phân cách (separator) được chỉ định.
Ví dụ:
a = "Hello, World!"
print(a.split(","))
# Kết quả: ['Hello', ' World!']
12.2 Nối chuỗi (concatenate strings)
Để nối hoặc kết hợp hai hay nhiều chuỗi lại với nhau, bạn có thể sử dụng toán tử +.
Ví dụ
Gộp biến a và biến b thành biến c:
a = "Hello"
b = "World"
c = a + b
print(c)
# Kết quả: "HelloWorld"
Ví dụ
Để thêm khoảng cách giữa hai từ, hãy cộng thêm một chuỗi trống " ":
c = a + " " + b
print(c)
# Kết quả: "Hello World"
12.3 Định dạng chuỗi (format strings)
Như đã học ở phần trước, chúng ta không thể nối trực tiếp một chuỗi với một số bằng toán tử + như thế này:
age = 15
txt = "Toi la Teo. Tuoi: " + age
# Sẽ gây ra lỗi
Để sửa lỗi trên, chúng ta sử dụng định dạng chuỗi của Python (f-strings). Bạn chỉ cần thêm chữ f trước dấu ngoặc kép và đặt các biến vào trong dấu ngoặc nhọn {}.
Ví dụ
age = 15
txt = f"Toi la Teo. Tuoi: {age}"
print(txt)
Bộ giữ chỗ (placeholder) và Bộ sửa đổi (modifier)
Ngoài ra, bên trong dấu {}, bạn có thể chứa biến, phép tính, hàm và các bộ sửa đổi định dạng.
Ví dụ
Sử dụng bộ sửa đổi: .2f để lấy 2 chữ số thập phân:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
# Kết quả: "The price is 59.00 dollars"
Ví dụ
Thực hiện phép tính toán ngay trong placeholder:
txt = f"The price is {20 * 59} dollars"
print(txt)
# Kết quả: "The price is 1180 dollars"
12.4 Dấu xuyệt ngược
Để chèn những ký tự "đặc biệt" vào chuỗi (ví dụ: dấu ngoặc kép bên trong một chuỗi cũng được bao bởi dấu ngoặc kép), chúng ta sử dụng dấu xuyệt ngược (\).
Ví dụ
Cách dùng sai (gây lỗi):
txt = "Hoc la mot cach "dau tu" cho tuong lai!"
Cách dùng đúng với \":
txt = "Hoc la mot cach \"dau tu\" cho tuong lai!"
print(txt)
Trong lập trình một số ký tự đặc biệt, hay ký tự chức năng (tiếng Anh là escape characters), nghĩa là khi gặp các ký tự này, Python sẽ thực hiện một chức năng nào đó.
Ví dụ:
- \': Dấu nháy đơn
- \": Dấu nháy kép
- \\: Dấu xuyệt ngược
- \n: Tạo dòng mới (xuống dòng)
- \t: Dấu Tab (khoảng cách rộng)
- \b: Xóa ngược (backspace)
Ví dụ
txt = "Hoc \n la mot cach \ndau tu \ncho tuong lai!"
print(txt)
#Hoc
# la mot cach
#dau tu
#cho tuong lai!
12.5 Danh sách các phương thức xử lý chuỗi
Python cung cấp rất nhiều phương thức (built-in methods) để bạn có thể sử dụng để xử lý chuỗi.
Lưu ý: Tất cả các phương thức xử lý chuỗi đều trả về giá trị mới. Chúng không làm thay đổi chuỗi gốc ban đầu.
Các phương thức:
12.6 Bài tập và câu hỏi
Bài tập 12a. Viết chương trình nhập vào s1, s2; tạo s3 bằng cách chèn s2 vào giữa s1.
Đầu vào:
Nhap chuoi s1: abcd
Nhap chuoi s2: xyz
Kết quả mong đợi:
Chuoi ket qua s3: abxyzcd
Bài tập 12b. Định dạng mã số học sinh
Yêu cầu: Viết chương trình cho người dùng nhập vào mã số viết tắt (chỉ phần số) và tên trường (viết thường). Chương trình sẽ tự động chuyển tên trường thành chữ hoa và thêm các số 0 vào trước mã số để đủ 6 ký tự, sau đó nối chúng lại.
- Gợi ý: Sử dụng upper() và zfill()
Đầu vào:
Nhap ma so: 123
Nhap ten truong: btx
Kết quả mong đợi:
Ma hoc sinh: BTX000123
Bài tập 12c. Đếm và thay thế từ khóa
Yêu cầu: Viết chương trình cho người dùng nhập vào một đoạn văn bản ngắn và một từ khóa cần tìm. Hãy cho biết từ khóa đó xuất hiện bao nhiêu lần và in ra đoạn văn bản mới sau khi đã thay thế từ khóa đó bằng dấu sao ***.
- Gợi ý: Sử dụng count() và replace()
Đầu vào:
Nhap doan van: hoc lap trinh python rat vui, hoc python giup tu duy tot
Nhap tu khoa: python
Kết quả mong đợi:
So lan xuat hien: 2
Van ban moi: hoc lap trinh *** rat vui, hoc *** giup tu duy tot
Bài tập 12d. Chuẩn hóa tiêu đề sách
Yêu cầu: Khi nhập liệu, người dùng thường gõ thừa khoảng trắng ở hai đầu và viết hoa lộn xộn. Viết chương trình nhập vào một tên sách, thực hiện xóa khoảng trắng dư thừa ở hai đầu và chuyển đổi chuỗi đó về dạng tiêu đề (viết hoa chữ cái đầu mỗi từ).
- Gợi ý: Sử dụng strip() và title().
Đầu vào:
Nhap ten sach: lap trinh python can ban
Kết quả mong đợi:
Ten sach chuan hoa: Lap Trinh Python Can Ban
Câu hỏi 12.1 Cú pháp nào đúng để in chuỗi ở dạng in hoa?
A. 'Welcome'.upper()
B. 'Welcome'.toUpper()
C. 'Welcome'.toUpperCase()
D. 'Welcome'.setUpper()
Câu hỏi 12.2 Điền vào chỗ trống để loại bỏ khoảng trắng dư thừa ở hai đầu:
txt = " Hello World "
x = _______
A. txt.split()
B. txt.strip()
C. txt.trim()
D. trim(txt)
Câu hỏi 12.3 Các biến x và y đang chứa dữ liệu kiểu chuỗi. Cú pháp nào để nối biến x và y thành z?
A. z = x, y
B. z = x = y
C. z = x + y
D. z = x * y
12.4 Kết quả của đoạn mã sau là gì?
x = 'Welcome', y = 'Coders', print(x + y)
A. Welcome Coders
B. WelcomeCoders
C. Welcome (xuống dòng) Coders
D. Welcome+Coders
12.5 Nếu x = 9, cú pháp nào in ra: The price is 9.00 dollars?
A. print(f'The price is {x:.2f} dollars')
B. print(f'The price is {x:2} dollars')
C. print(f'The price is {x:format(2)} dollars')
D. print("The price is {x:.2f} dollars")
12. String Operations (Continued)
In the previous lesson, you performed several operations on strings, such as checking if a substring exists within a string using the in and not in keywords, as well as string slicing.
In this section, we will explore additional string manipulation techniques.
12.1 Modifying Strings
Python provides a set of built-in methods that allow you to handle strings easily.
Upper case
The upper() method returns the string with all characters converted to upper case.
Example:
a = "Van Teo"
print(a.upper())
# Output: "VAN TEO"
Lower case
The lower() method returns the string with all characters converted to lower case.
Example:
a = "Van Teo"
print(a.lower())
# Output: "van teo"
Remove whitespace
Extra whitespace refers to spaces before and/or after the actual text. The strip() method removes any leading and trailing whitespace from the string.
Example:
a = " Hello, World! "
print(a.strip())
# Output: "Hello, World!"
Replace string
The replace() method replaces a specified substring with another substring.
Example:
a = "Hello, World!"
print(a.replace("H", "J"))
# Output: "Jello, World!"
Split string
The split() method returns a list where the elements are substrings separated by a specified separator.
Example:
a = "Hello, World!"
print(a.split(","))
# Output: ['Hello', ' World!']
12.2 Concatenate Strings
To join or combine two or more strings, you can use the + operator.
Example
Combine variable a and variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
# Output: "HelloWorld"
Example
To add a space between them, add a whitespace string " ":
c = a + " " + b
print(c)
# Output: "Hello World"
12.3 Format Strings
As learned previously, we cannot directly concatenate a string with a number using the + operator like this:
age = 15
txt = "I am Teo. Age: " + age
# This will cause an Error
To fix this, we use Python's f-strings. Simply add the letter f before the quotation marks and place variables inside curly brackets {}.
Example:
age = 15
txt = f"I am Teo. Age: {age}"
print(txt)
Placeholders and modifiers
Additionally, inside the {} (placeholder), you can include variables, mathematical operations, functions, and formatting modifiers.
Example
Using the modifier :.2f to display 2 decimal places:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
# Output: "The price is 59.00 dollars"
Example
Performing a calculation directly inside the placeholder:
txt = f"The price is {20 * 59} dollars"
print(txt)
# Output: "The price is 1180 dollars"
12.4 Backslashes (Escape Characters)
To insert "special" characters into a string (for example, double quotes inside a string that is already enclosed in double quotes), we use the backslash \.
Example
Incorrect usage (causes an error):
txt = "Learning is an "investment" for the future!"
Example
Correct usage with \":
txt = "Learning is an \"investment\" for the future!"
print(txt)
In programming, these are called escape characters. When Python encounters them, it performs a specific function.
Common escape characters:
- \': Single Quote
- \": Double Quote
- \\: Backslash
- \n: New Line (Moves text to the next line)
- \t: Tab (Creates a wide space)
- \b: Backspace
Example
txt = "Learning \n is an \ninvestment \nfor the future!"
print(txt)
# Output:
# Learning
# is an
# investment
# for the future!
12.5 List of String Methods
Python provides many built-in methods for string manipulation.
Note: All string methods return a new value. They do not modify the original string (Strings are immutable).
12.6 Exercises and Questions
Exercise 12a. Write a program to input s1 and s2; create s3 by inserting s2 into the middle of s1.
Input:
s1: abcd
s2: xyz
Expected Output:
abxyzcd
Exercise 12b. Student ID Formatting
Requirement: Write a program where the user enters a numeric ID and a school name (in lower case). The program should convert the school name to upper case and pad the ID with leading zeros to reach 6 characters, then concatenate them.
Input:
ID: 123
School: btx
Expected Output:
BTX000123
Exercise 12c. Count and Replace Keywords
Requirement: Write a program to input a short text and a keyword. Display how many times the keyword appears and print the new text after replacing the keyword with three asterisks ***.
Input:
Text: learning python is fun, python helps logic,
Keyword: python
Expected Output:
Count: 2
New Text: learning *** is fun, *** helps logic
Exercise 12d. Book Title Normalization
Requirement: Users often enter extra spaces and inconsistent casing. Write a program to input a book title, remove leading/trailing spaces, and convert it to Title Case.
Input:
basic python programming
Expected Output:
Basic Python Programming
Question 12.1 Which syntax correctly prints a string in upper case?
A. 'Welcome'.upper()
B. 'Welcome'.toUpper()
C. 'Welcome'.toUpperCase()
D. 'Welcome'.setUpper()
Question 12.2 Fill in the blank to remove leading and trailing whitespace:
x = txt._______
A. split()
B. strip()
C. trim()
D. trim(txt)
Question 12.3 Which syntax concatenates string variables x and y into z?
A. z = x, y
B. z = x = y
C. z = x + y
D. z = x * y
Question 12.4 What is the result of x = 'Welcome', y = 'Coders', print(x + y)?
A. Welcome Coders
B. WelcomeCoders
C. Welcome\nCoders
D. Welcome+Coders
Question 12.5 If x = 9, which syntax prints: The price is 9.00 dollars?
A. print(f'The price is {x:.2f} dollars')
B. print(f'The price is {x:2} dollars')
C. print(f'The price is {x:format(2)} dollars')
D. print("The price is {x:.2f} dollars")