Logo

Personal Ops Runbook

Personal runbook covering infrastructure operations for Cloud, Kubernetes, OpenStack, and Ceph environments. Includes deployment and teardown procedures, node management, cluster monitoring setup, and incident response workflows compiled from day-to-day operational work. Intended strictly for personal reference — configurations and scripts are environment-specific and not guaranteed to work as-is elsewhere.

[Python] Lesson 26 – String format


String formatting trong Python là cách để chèn một giá trị hoặc nhiều giá trị vào trong một chuỗi string để tạo ra một chuỗi mới. Có nhiều cách để format một chuỗi trong Python, dưới đây là 3 ví dụ phổ biến:

  1. Sử dụng cú pháp f-string:
name = 'Alice'
age = 30
print(f'My name is {name} and I am {age} years old.')
  1. Sử dụng cú pháp format():
name = 'Bob'
age = 25
print('My name is {} and I am {} years old.'.format(name, age))

Output: My name is Bob and I am 25 years old.

  1. Sử dụng cú pháp %:
name = 'Charlie'
age = 20
print('My name is %s and I am %d years old.' % (name, age))

Output: My name is Charlie and I am 20 years old.

Trong các ví dụ trên, {} được sử dụng để đánh dấu vị trí mà giá trị sẽ được chèn vào trong chuỗi, %s%d được sử dụng để định dạng chuỗi và số nguyên, và f-string được sử dụng để tạo ra một chuỗi mới với giá trị được chèn vào trong chuỗi.

Một ví dụ về sử dụng string format trong Python trong môi trường Linux là để hiển thị các thông tin về file. Ví dụ, nếu chúng ta muốn hiển thị tên file, kích thước và đường dẫn đến file, chúng ta có thể sử dụng string format để định dạng chuỗi như sau:

filename = "file.txt"
filepath = "/home/user/files/file.txt"
filesize = 1024

print("File name: {}\nFile path: {}\nFile size: {} bytes".format(filename, filepath, filesize))

Kết quả sẽ là:

File name: file.txt
File path: /home/user/files/file.txt
File size: 1024 bytes

Trong đó, {} được sử dụng để đánh dấu vị trí mà giá trị của biến sẽ được chèn vào chuỗi. Các biến được truyền vào hàm format() theo thứ tự tương ứng.