English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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 :
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')
Elle ne renvoie aucune valeur. RetourneNone.
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.
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.
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.