10. Chuỗi
Ở các bài học trước, chúng ta đã được làm quen với kiểu dữ liệu số, đã biết làm việc với biến, đã biết sử dụng hàm input() để nhập dữ liệu từ bàn phím.
Phần này, chúng ta sẽ làm quen với một kiểu dữ liệu mới là kiểu chuỗi, đồng thời ôn lại cách làm việc với biến, với hàm input().
10.1 Chuỗi là gì?
Chuỗi (string) là một dãy các ký tự. Ký tự ở đây có thể là chữ cái (a, b, c...), chữ số (1, 2, 3...), ký hiệu (@, #, $...) hay thậm chí là khoảng trắng.
Trong Python, để máy tính hiểu đâu là một chuỗi, chúng ta phải đặt dãy ký tự đó bên trong cặp dấu nháy đơn (' ') hoặc cặp dấu nháy kép (" ").
Ví dụ:
- "Chào bạn!" là một chuỗi
- 'Python 123' cũng là một chuỗi
- 123 (không có dấu nháy) là kiểu dữ liệu số (integer), không phải chuỗi
Bạn hãy lập trình, sử dụng hàm type() để kiểm tra lại kiểu dữ liệu. Kiểu dữ liệu chuỗi trong Python kí hiệu là str (viết tắt của chữ string).
print(type("Chao ban!"))
// <class 'str'>
print(type('Python 123'))
// <class 'str'>
print(type(123))
// <class 'int'>
Dấu nháy lồng nhau
Bạn có thể lồng dấu nháy đơn và dấu nháy kép trong một chuỗi, miễn là dấu nháy bên trong không trùng với dấu nháy phía ngoài.
Ví dụ:
print("It's my computer")
// It's my computer
print("Hoc nhieu duoc goi la 'cham chi'")
// Hoc nhieu duoc goi la 'cham chi'
print('Hoc nhieu duoc goi la "cham chi"')
// Hoc nhieu duoc goi la 'cham chi'
Khai báo chuỗi với biến
Cũng giống như số, chúng ta có thể lưu trữ chuỗi vào trong các biến, để sử dụng nhiều lần.
Ví dụ:
tenTruong = "THCS Bui Thi Xuan"
monHoc = 'Lap trinh Python'
print(tenTruong)
print(monHoc)
Nhập chuỗi từ bàn phím với hàm input()
Ở bài trước, bạn đã biết hàm input() dùng để nhận dữ liệu từ người dùng.
Ví dụ:
hoTen = input("Nhap ho ten của bạn: ")
print("Chao ban ", hoTen)
Bạn lưu ý là, mặc định, mọi dữ liệu nhập vào từ hàm input() đều được Python hiểu là kiểu chuỗi.
Ví dụ: Ngay cả khi bạn nhập số 10 vào input(), Python vẫn coi đó là chuỗi "10".
tuoi = input("Tuoi cua ban:")
// Tuoi cua ban:10
print(type(tuoi))
// <class 'str'>
Do dữ liệu nhập từ bàn phím luôn là kiểu chuỗi, do vậy, nếu bạn muốn tính toán thì bạn phải đổi chuỗi sang số bằng hàm int(). Ví dụ, bạn hãy lập trình và chạy đoạn mã sau:
diemVan = input("Diem mon Van:")
// Diem mon Van: 7
diemToan = input("Diem mon Toan:")
// Diem mon Toan:8
DiemTB = (diemVan + diemToan)/2
Khi chạy đoạn mã trên, bạn sẽ nhận được lỗi sau:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
DiemTB = (diemVan + diemToan)/2
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Bạn cần phải đổi kiểu dữ liệu nhập vào, trước khi có thể thực hiện tính toán:
Bạn hãy lập trình lại như sau:
diemVan = int(input("Diem mon Van:"))
// Diem mon Van:7
diemToan = int(input("Diem mon Toan:"))
// Diem mon Toan:8
diemTB = (diemVan + diemToan)/2
print("Diem TB:", diemTB)
// Diem TB: 7.5
Chuỗi nhiều dòng
Nếu bạn muốn viết một đoạn văn dài có xuống dòng, Python hỗ trợ cặp ba dấu nháy kép (""" """) hoặc ba dấu nháy đơn (''' ''').
Ví dụ, bạn hãy khai báo một chuỗi gồm nhiều dòng, và xuất ra màn hình:
gioi_thieu = """Minh dang hoc Python
tai phong lab Langbiang.
Rat vui duoc lam quen!"""
print(gioi_thieu)
10.2 Chuỗi là một mảng
Khi bạn khai báo và gán một chuỗi cho một biến (ví dụ ten), Python sẽ coi đặt chuỗi bạn vừa khai báo vào một mảng. Hay nói cách khác, chuỗi chính là một mảng (dãy), tiếng Anh là array.
Bạn hiểu đơn giản: mảng là một dãy các ô để chứa dữ liệu. Với dữ liệu kiểu chuỗi, Python sẽ dùng mỗi ô để chứa mỗi ký tự của chuỗi. Xem hình minh họa:
Ở hình trên:
Bạn khai báo và gán cho biến ten chuỗi "van teo"
ten = "van teo"
Khi đó, Python sẽ dùng một dãy gồm 7 ô để chứa các ký tự của chuỗi ten.
Mỗi ô của mảng có một địa chỉ, được đánh từ 0, 1, 2, ….
Ví dụ, ô [0] sẽ chứa chữ ‘v’, ô [6] sẽ chứa chữ ‘o’.
Bạn hãy lập trình để kiểm tra:
print(ten[0])
// v
print(ten[6])
// o
Duyệt từng phần tử của chuỗi
Vì chuỗi là một mảng, nên bạn có thể duyệt qua từng ký tự của chuỗi bằng vòng lặp for.
Ví dụ:
for x in ten:
print(x)
// v
// a
// n
//
// t
// e
// o
Làm sao để biết chiều dài của một chuỗi?
Bạn có thể sử dụng hàm len() của python để biết được chiều dài của chuỗi.
Ví dụ:
print(len(ten))
// 7
Lưu ý: khoảng trắng của chuỗi cũng được tính là một ký tự.
Bài tập 10a. Nhập một chuỗi bất kỳ từ bàn phím. Dùng vòng lặp for để xuất từng ký tự của chuỗi ra màn hình.
Mô tả yêu cầu
Nhập:
str = input("Ban nhap mot chuoi bat ky:")
// van teo
Xuất
str[0] = v
str[1] = a
str[2] = n
str[3] =
str[4] = t
str[5] = e
str[6] = o
Bài tập 10b. Nhập một chuỗi bất kỳ, bạn hãy dùng vòng lặp for để tính chiều dài của chuỗi. Lưu ý: không được sử dụng hàm len().
Mô tả yêu cầu
Nhập:
Ban nhap mot chuoi bat ky:
// van teo
Xuất:
// 7
Câu hỏi 10.1 Cho biết kết quả của đoạn mã sau:
x = 'Welcome'
print(x[3])
A. Wel
B. l
C. c
D. Welcome Welcome Welcome
Câu hỏi 10.2 Cho biết kết quả của đoạn mã sau:
print('10' + 10)
A. 20
B. Thông báo lỗi
C. 1010
D. '1010'
10. Strings
In previous lessons, we introduced numeric data types, learned how to work with variables, and used the input() function to get data from the keyboard. In this section, we will explore a new data type called Strings, while reviewing how to handle variables and the input() function.
10.1 What is a String?
A string is a sequence of characters. These characters can be letters (a, b, c...), digits (1, 2, 3...), symbols (@, #, $...), or even whitespace (spaces). In Python, to define a string, we must enclose the sequence of characters in either single quotes (' ') or double quotes (" ").
Examples:
- "Hello friend!" is a string
- 'Python 123' is also a string
- 123 (without quotes) is an integer (numeric data type), not a string
You can use the type() function to verify the data type. In Python, the string type is denoted as str.
print(type("Hello friend!"))
# <class 'str'>
print(type('Python 123'))
# <class 'str'>
print(type(123))
# <class 'int'>
Nested Quotes
You can nest single quotes inside double quotes (and vice versa), as long as the inner quotes differ from the outer ones.
Examples:
print("It's my computer")
# It's my computer
print("Learning a lot is called 'diligent'")
# Learning a lot is called 'diligent'
print('Learning a lot is called "diligent"')
# Learning a lot is called "diligent"
Declaring strings with variables
Just like numbers, we can store strings in variables for reuse.
school_name = "Bui Thi Xuan Secondary School"
subject = 'Python Programming'
print(school_name)
print(subject)
Getting string using input()
By default, all data received from the input() function is treated as a string by Python. Even if you enter a number like 10, Python treats it as the string "10".
age = input("Enter your age: ")
# Enter your age: 10
print(type(age))
# <class 'str'>
Because keyboard input is always a string, you must typecast (convert) the string to a number using the int() function before performing calculations. Otherwise, you will encounter a TypeError.
Incorrect way:
math_score = input("Math score: ") # Returns a string
literature_score = input("Literature score: ") # Returns a string
average = (math_score + literature_score) / 2
# Error: TypeError: unsupported operand type(s) for /: 'str' and 'int'
Correct way:
math_score = int(input("Math score: "))
literature_score = int(input("Literature score: "))
average = (math_score + literature_score) / 2
print("Average Score:", average)
# Average Score: 7.5
Multi-line strings
To write long paragraphs with line breaks, Python supports triple quotes (""" """ or ''' ''').
introduction = """I am learning Python
at Langbiang Lab.
Nice to meet you!"""
print(introduction)
10.2 Strings as arrays
When you assign a string to a variable, Python treats that string as an array (a sequence) of characters. Think of an array as a series of slots. In a string, Python uses each slot to store one character.
In the illustration above: If you assign name = "van teo", Python uses 7 slots. Each slot has an index (address) starting from 0, 1, 2…
- Index [0] contains 'v'
- Index [6] contains 'o'
Example:
name = "van teo"
print(name[0]) # Output: v
print(name[6]) # Output: o
Looping through a string
Since a string is an array, you can iterate through its characters using a for loop.
for x in name:
print(x)
String Length
Use the len() function to find the number of characters in a string. Note: Whitespace counts as a character.
print(len(name))
# Output: 7
10.3 Exercises and Questions
Exercise 10a: Input a string from the keyboard. Use a for loop to print each character along with its index.
- Input:
van teo
- Output:
str[0] = v
str[1] = a
…
Exercise 10b: Input a string and use a for loop to calculate its length without using the len() function.
Question 10.1: What is the result of the following code?
x = 'Welcome'
print(x[3])
A. Wel
B. l
C. c
D. Welcome Welcome Welcome
Question 10.2: What is the result of the following code?
print('10' + 10)
A. 20
B. Error Message (TypeError)
C. 1010
D. '1010'
