Strings — slicing, formatting, built-ins | Lập trình Python

DevNotes
By -
0

 

1. String Slicing (Cắt chuỗi string)


text = "Python Programming"

print(text[0:6])  # 'Python' → lấy chữ từ index 0 - 5
print(text[:6])  # 'Python' → bắt đầu là tuỳ chọn chỉ cần chỉ số cuối
print(text[7:])  # 'Programming' → lấy từ chỉ số 7 về sau
print(text[-11:-1])  # 'Programmin' → đếm từ phải sang trái
print(text[::-1])  # 'gnimmargorP nohtyP' → Đảo string

2. String Formatting - Định dạng chuỗi

Kiểu cũ :

Sử dụng %

# Dùng %s cho string và %d cho số
name = "Alice"
age = 25
print("My name is %s and I am %d years old" % (name, age)) # My name is Alice and I am 25 years old

Sử dụng {}


# str.format() dùng {} để thay thế vị trí xuất hiện của biến
print("My name is {} and I am {} years old.".format(name, age))
# str.format() Trỏ theo index
print("My name is {1} and I am {0} years old".format(age, name))

Kiểu mới:

Sử dụng f-Strings (Python 3.6+) ✅

print(f"My name is {name} and I am {age} years old.")
pi = 3.14159
print(f"PI rounded = {pi:.2f}")

3. Một số Function dựng sẵn của String


Một số ví dụ code mẫu

name = "Hello World !"
print(len(name)) # Lấy số ký tự
print(name.lower()) # Chuyển sang chữ thường
print(name.upper()) # Chuyển sang chữ Hoa
# Kết quả
"""
13
hello world !
HELLO WORLD !
"""

Đăng nhận xét

0 Nhận xét

Đăng nhận xét (0)
3/related/default