Phương thức định dạng chuỗi Python()
Ví dụ
Chèn giá vào bên trong phần giữ chỗ, giá phải ở dạng dấu phẩy cố định, định dạng hai thập phân:
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
Hãy tự mình thử »Định nghĩa và cách sử dụng
Phương thức format()
định dạng (các) giá trị đã chỉ định và chèn chúng vào trong phần giữ chỗ của chuỗi.
Trình giữ chỗ được xác định bằng dấu ngoặc nhọn: {}. Đọc thêm về trình giữ chỗ trong phần Trình giữ chỗ bên dưới.
Phương thức format()
trả về chuỗi đã được định dạng.
Cú pháp
string .format( value1, value2... )
Giá trị tham số
Parameter | Description |
---|---|
value1, value2... | Required. One or more values that should be formatted and inserted in
the string. The values are either a list of values separated by commas, a key=value list, or a combination of both. The values can be of any data type. |
Trình giữ chỗ
Các phần giữ chỗ có thể được xác định bằng cách sử dụng các chỉ mục có tên {price}
, các chỉ mục được đánh số {0}
hoặc thậm chí các phần giữ chỗ trống {}
.
Ví dụ
Sử dụng các giá trị giữ chỗ khác nhau:
txt1 = "My
name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My
name is {0}, I'm {1}".format("John",36)
txt3 = "My
name is {}, I'm {}".format("John",36)
Hãy tự mình thử »Các loại định dạng
Bên trong phần giữ chỗ, bạn có thể thêm loại định dạng để định dạng kết quả:
:< | Try it | Left aligns the result (within the available space) |
:> | Try it | Right aligns the result (within the available space) |
:^ | Try it | Center aligns the result (within the available space) |
:= | Try it | Places the sign to the left most position |
:+ | Try it | Use a plus sign to indicate if the result is positive or negative |
:- | Try it | Use a minus sign for negative values only |
: | Try it | Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) |
:, | Try it | Use a comma as a thousand separator |
:_ | Try it | Use a underscore as a thousand separator |
:b | Try it | Binary format |
:c | Converts the value into the corresponding unicode character | |
:d | Try it | Decimal format |
:e | Try it | Scientific format, with a lower case e |
:E | Try it | Scientific format, with an upper case E |
:f | Try it | Fix point number format |
:F | Try it | Fix point number format, in uppercase format (show inf and nan as INF
and NAN ) |
:g | General format | |
:G | General format (using a upper case E for scientific notations) | |
:o | Try it | Octal format |
:x | Try it | Hex format, lower case |
:X | Try it | Hex format, upper case |
:n | Number format | |
:% | Try it | Percentage format |