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

Notes d'expérience

Outils en ligne

Fonctions en Python

Types de données en Python

Tutoriel de base Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Python built-in functions

Utilisation et exemples de la fonction print() en Python

La fonction print() écrit les objets donnés sur l'appareil de sortie standard (écran) ou dans un fichier flux de texte.

print(*La syntaxe complète de print() est :

objects, sep=' ', end='\n', file=sys.stdout, flush=False)

  • print() paramètres-objets.*Indique que plusieurs objets peuvent être présents

  • sep-Les objets sont séparés par Sep.Valeur prédéfinie: ''

  • end-end est le dernierImprimer

  • file-Doit être un objet avec une méthode write(string). Si omis, sys.stdout utilisera cela pour imprimer l'objet sur l'écran.

  • flush-Si elle est True, le flux est forcé à se rafraîchir.Valeur par défaut: False

Attention :sep,end,fileandflushSont des paramètres nommés. Si vous voulez utilisersepLes paramètres, il faut utiliser :

print(*objects, sep = 'separator')

Ne peut pas utiliser

print(*objects, 'separator')

La fonction print() renvoie une valeur

Elle ne renvoie aucune valeur. RetourneNone.

Example1Comment fonctionne la fonction print() en Python ?

print("Python is fun fr.oldtoolbag.com)
a = 5
# Passed two objects
print("a =", a)
b = a
# Pass three objects
print('a =', a, '= b')

When running the program, the output is:

Python is fun fr.oldtoolbag.com
a = 5
a = 5 = b

In the above program, onlyobjectparameters passed to the print() function (in all three print statements).

Therefore,

  • Using a space separator. Note the space between two objects in the output.

  • Using endParameter '\n' (newline). Note that each print statement displays the output on a new line.

  • fileis sys.stdout. The output is displayed on the screen.

  • flushis False. The stream is not flushed.

Example2: print() with separator and end parameter

a = 5
print("a =", a, sep='00000', end='


')
print("a =", a, sep='0', end='')

When running the program, the output is:

a = 000005
a = 05

We passedsepandendParameter.

Example3: print() with file parameter

In Python, you can specifyfilethe parameter willobjectprint toin the file.

Recommended reading: Python file I / O

sourceFile = open('python.txt', 'w')
print('very cool, hahaha!', file=sourceFile)
sourceFile.close()

the program tries to open it in write modepython.txt. If this file does not exist,it willCreatepython.txtthe file in write mode.

Here, we have openedsourceFileThe file object is passed tofileParameters. The string object 'very cool, hahaha!' is printed and written topython.txtFile (check it in the system).

Finally, use the close() method to close the file.

Python built-in functions