English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemples de format() en Python

Python built-in functions

La méthode intégrée format() formate la valeur spécifiée en fonction du format spécifié.

La méthode format() est similaire àFormatage de chaîneMéthode. À l'intérieur, ces deux méthodes appellent la méthode __format__() de l'objet.

La méthode intégrée format() est une implémentation interne de bas niveau pour le formatage des objets, tandis que la méthode format() de chaîne est une implémentation avancée permettant de réaliser des opérations de formatage complexes sur plusieurs objets de chaîne.

La syntaxe de format() est :

format(value[, format_spec])

Paramètres de format()

La méthode format() utilise deux paramètres :

  • value -Valeur à formater

  • format_spec-Norme pour configurer le format des valeurs.

Les indicateurs de format peuvent être utilisés dans le format suivant :

[[remplissage]alignement][signe][#][0][width][,][.precision][type]
où les options sont
remplissage ::= tout caractère
alignement ::= "<" | ">" | "=" | "^"
signe ::= ""+" | "-" | "
width ::= entier
precision ::= entier
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Vous pouvez en savoir plus surType de formatetAlignementPlus d'informations.

Retourne la valeur formatée

La méthode format() formate la valeur spécifiée en fonction du format spécifié.

Example1:utiliser format() pour formater les nombres

# d, f et b sont des types
# Integer
print(format(123, "d"))
# Floating-point parameters
print(format(123.4567898, "f"))
# Binary parameters
print(format(12, "b"))

When running the program, the output is:

123
123.456790
1100

Example2: Use padding, alignment, sign, width, precision, and type to format numbers

# Integer
print(format(1234, "*>+7,d"))
# Floating-point parameters
print(format(123.4567, "^-09.3,f"))

When running the program, the output is:

*+1,234
0123.4570

Here, when formatting integers1234When we specify the format specifier* <+ 7,d. Let's look at the meaning of each option:

  • * -The padding character is used to fill spaces after formatting

  • > -This is the right alignment option, which can align the output string to the right

  • + -This is a sign option used to force the number to be signed (with a sign on the left)

  • 7-The width option can force the number to adopt the minimum width7, other spaces will be filled with padding characters

  • , -The comma operator places a comma between all the thousands.

  • d -It is a type option used to specify numbers as integers.

Formatting floating-point numbers123.4567When we specify the format specifier ^ -09.3f. These are:

  • ^ -This is the center alignment option, which can align the output string to the center of the remaining space

  • --The sign option only forces the use of a sign to display negative numbers

  • 0-It is a character used to replace spaces.

  • 9-Use the width option to set the minimum width of the number9(including the decimal point, comma in the thousands, and sign)

  • .3-The precision operator sets the precision of the given floating-point number to3Bit

  • f -It is a type option used to specify numbers as floating-point numbers.

Example3: Use __format__() to overwrite using format()

# Custom __format__() method
class Person:
    def __format__(self, format):
        if(format == 'age'):
            return ''23'
        return 'None'
print(format(Person(), "age"))

When running the program, the output is:

23

Here, we have overridden the __format__() method of the Person class.

Now, it accepts the parameter code> age to return23. If no format is specified, None is returned.

The format() method runs internally Person().__format__("age") returns23.

Python built-in functions