Thứ Tư, Tháng Hai 12, 2025
spot_img
Homeformat() function in Python - QuanTriMang.com

format() function in Python – QuanTriMang.com

What is the Format function in Python? How to use Python format how? Let's find out together!

Python is a popular programming language today because it is easy to learn, apply and develop. All thanks to its great features for programming.

In the Python language, we have a rich collection of built-in methods and functions. These functions are very useful, providing an easy and elegant way to write code, one such method is format() in Python. It provides the functionality to format values ​​the way the user wants by mentioning the representation in the format specifier.

The Python format function is very useful, and provides a convenient way to format numbers. For example, it provides an elegant way to convert integers to binary format, to set precision, alignment, and more. This article will provide detailed information, including the concept of all format() function implementations with examples in Python programming.

Format Python What is that? This is a question that many Python learners are interested in. The format() function is a powerful tool that allows programmers to create formatted strings by embedding variables and values ​​in placeholders in the template string. This method provides a flexible and comprehensive way to structure text output for a variety of applications. The Python string format() function was introduced to handle complex string formatting more efficiently. Sometimes you may want to create generic print jobs within the field instead of writing the print job each time using formatting concepts.

Syntax of format() function in Python:

format(value[, format_spec])

Parameters of format() function

The format() function has 2 parameters:

  • value: value to be formatted.
  • format_spec: the format you want for value. value.

Format sets:

Type Describe
Left align the result
^ Center the result
> Right-align the result
= Place a positive (+) or negative (-) sign close to the left margin
d Integer format
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lowercase)
X Hexadecimal format (upper case)
n Decimal number format
e Hat symbol. (lowercase e)
E Hat symbol. (uppercase E)
f Floating point number format (Default: 6)
F Similar to 'f', but displays upper case, for example 'inf' is 'INF' and 'nan' is 'NAN'
g General format. Round the number to p significant digits. (Default: 6)
G Similar to 'g', switch to 'E' if the number is too large.
% Percentage.

The formatter has the following order:

[[fill]align][sign][#][0][width][,][.precision][type]

In there:

  • fill: is any character
  • align: align, “” | “=” | “^”
  • sign: sign, “+” | “-” | ” “
  • width: string length, which is an integer
  • precision: precision, is an integer
  • type: format style, “b” | “c” | “d” | “e” | “E” | “f” | “F” | “g” | “G” | “n” | “o” | “s” | “x” | “X” | “%”

Return value from format()

The format() method returns the formatted result of a given value specified by the specified formatter.

Example 1: Format numbers with format()

# d, f và b là loại định dạng

# số nguyên
print(format(123, "d"))

# số thập phân
# viết bởi Quantrimang.com
print(format(123.4567898, "f"))

# nhị phân
print(format(12, "b"))

Run the program, the returned results are:

123
123.456790
1100

Example 2: Format numbers with alignment

# số nguyên 
print(format(1234, "*>+7,d"))

# số thập phân
print(format(123.4567, "^-09.3f"))

Output returned:

*+1,234
0123.4570

Here, when formatting the integer 1234, we specify the include formatter *. Tại sao lại như vậy? Chi tiết như sau:

  • * Fill character, fills empty spaces after formatting.
  • > Right alignment option, so the output string is on the right.
  • + Option to force the output number to have a sign (with the sign on the left).
  • 7 The option specifies the length of the result, forcing the returned number to have a minimum length of 7 characters, other spaces will be filled with fill characters.
  • , Thousands operator, a comma will be placed between the thousands digit and the remaining digits.
  • d Optionally specifies the return result as an integer.

When formatting the floating point number 123.4567, we specify a formatter that includes ^-09.3fdetails are as follows:

  • ^ Center position alignment option, so the output string will be centered in the specified space.
  • - Option to force output numbers to display a negative sign.
  • 0 Characters added to spaces after formatting.
  • 9 The option specifies the length of the result, forcing the returned number to have a minimum length of 9 characters (including decimal points, commas and positive and negative signs).
  • .3 The precision operator, determines the precision, rounded to the 3rd digit after the decimal point.
  • f Optionally specifies the return result as a floating point number.

Example 3: Using format() by overriding __format__()

# phương thức __format __ () tùy chỉnh
class Person:
    def __format__(self, format):
        if(format == 'age'):
            return '23'
        return 'None'
print(format(Person(), "age"))

Run the program, the returned results are:

23

Here, we have overridden the method __format __() of class Person, and method format() inside run Person().__format__("age") to return 23.

Example 4: Using format() with list

Given a list of float values, this task truncates all float values ​​to 2 decimal places. Let's look at different methods to do this task.

# Code Python giảm giá trị float sang 2 chữ số thập phân.

# Khởi tạo danh sách
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]

# Dùng format
Output = ['{:.2f}'.format(elem) for elem in Input]

# In đầu ra
print(Output)

Result:

['100.77', '17.23', '60.99', '300.84']

Example 5: Use a dictionary to extract values ​​into placeholders in the string that needs to be formatted. Basically, we use ** to extract these values. The above method can be useful in string replacement, while preparing an SQL query.

introduction = 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'
full_name = {
'first_name': 'Tony',
'middle_name': 'Howard',
'last_name': 'Stark',
'aka': 'Iron Man',
}

# Lưu ý dùng toán tử "**" để giải nén các giá trị.
print(introduction.format(**full_name))

Result:

My name is Tony Howard Stark AKA the Iron Man.

See also: Built-in Python functions

Compare built-in format() and string format()

Jaw format() Similar to the string format method. Basically, both methods call __format__() of an object.

While the built-in format() function is a low-level implementation for formatting an object with __format__() internally, string format() is a higher-level implementation that can perform complex formatting operations on multiple strings of objects.

As you can see, using the format function in Python is not too difficult. As long as you grasp the basic knowledge above, you can use this command fluently.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments