Python programming languageprint()
Functions are the first output functions that beginners touch, but it's used for much more than simple text output. This article will take a closer lookprint()
The use of functions, including basic text output, formatted output, and some advanced usages, helps readers understand and use this important output function more comprehensively.
In Python, use:print()
The simplest way to do this function is to output a string:
pythoncopy codeprint("hello, world!")This will output on the console
hello, world!
。In addition,print()
Functions can also output multiple values at once, separated by commas:
pythoncopy codename = "john"age = 25print("name:", name, "age:", age)This will output
name: john age: 25
In the old python format, it is possible to usesymbol for placeholder substitution:
pythoncopy codename = "alice"age = 30print("name: %s, age: %d" % name, age))Here,
%s
Represents a string placeholder%d
Indicates an integer placeholder. The result will be:name: alice, age: 30
useformat()
method for string formatting:
pythoncopy codename = "bob"age = 22print("name: {age: {".format(name, age))This will output
name: bob, age: 22
。Indexes and keywords can be used within placeholders for enhanced formatting flexibility.
In addition to the output in the console,print()
You can also output content to a file. For example, outputting content tooutput.txt
Files:
pythoncopy codewith open("output.txt", "w") as file: print("this is written to a file", file=file)Can be used
sep
withend
parameter to set the delimiter and end of the output:
pythoncopy codeprint("one", "two", "three", sep=", ", end="!!!")This will output
one, two, three!!!
Python Programming: From Beginner to MasteryAuthor: Magnus Lie Hetland, Publisher: People's Posts and Telecommunications Publishing House, Year: 2021.
Python Core Programmingby Wesley JChun, Publisher: China Machine Press, Year: 2020.
print()
As one of the most commonly used output tools in Python programming, functions are rich in functionality and flexibility. By in-depth learning Xi its basic usage and advanced features, you can better grasp the output skills in python programming, and improve the readability and practicability of the **. I hope this article can help readers better understand and applyprint()
Function.