Home >Backend Development >Python Tutorial >Detailed explanation of examples of usage of Print() function in Python

Detailed explanation of examples of usage of Print() function in Python

WBOY
WBOYforward
2022-11-14 17:02:286655browse

This article brings you relevant knowledge about Python, which mainly introduces the relevant knowledge about the usage of print() function. The print() function is used to print output. One of the most common built-in functions in Python, let’s take a look at it, I hope it will be helpful to everyone.

Detailed explanation of examples of usage of Print() function in Python

[Related recommendations: Python3 video tutorial ]

print() function is used to print output and is the most common in python A built-in function.

1. The syntax of the print() function is as follows:

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

Will print out "objects" to the text stream specified by the "file parameter", separated by the "sep parameter" and add the "end parameter" at the end. "sep", "end", "file" and "flush" must be given as keyword arguments. The flush keyword parameter was added after version 3.3 of Phthon.

All non-keyword parameters will be converted to strings as if str() were executed, and will be written to the stream with the "sep parameter" and the "end parameter" at the end . Both the "sep parameter" and the "end parameter" must be strings; they can also be "None", which means the default value is used. If no "objects parameter" is given, print() will only write the "end parameter".

 The "file parameter" must be an object with a write(string) method; if the parameter does not exist or is None, sys.stdout will be used. Because the arguments to be printed are converted to text strings, print() cannot be used with file objects in binary mode. For these objects, file.write(...) should be used instead. Whether the output is cached usually depends on the file, but if the flush keyword argument is True, the output stream is forced to be flushed.

2. Print() prints out text

The printed text content is not only Chinese text, but also English text or text containing special symbols. When printing text, you need to use quotation marks. The text content is quoted. The quotation marks can be single quotation marks (' '), double quotation marks (" "), triple quotation marks (""" """)

#Triple quotedA pair of triple quotes, quoting multiple lines of textMultilinetext="""must do as they can.

Usage method

Code

Running result

Single quotes

A pair of single quotes, double quotes can be used inside the single quotes, and the single quotes can be printed out

print('Where there is life, there is hope')

Where there is life, there is hope



##print('"Where there is life, there is hope"')

"Where there is life, there is hope"





#Double quotes

A pair of double quotes, single quotes can be used inside the double quotes, and the single quotes can be printed out

print("Never be discouraged!")

Never be discouraged!



print("'Never be discouraged! '")

'Never be discouraged! '





They who cannot do as they would,

must do as they can.

If you cannot do as you wish, you must do your best.

"""

print(Multilinetext)

hey who cannot do as they would,

If you can’t do what you want,

you must try your best.


3. How to use spaces in print()

#2Use commas between two adjacent items Intervalprint("It depends on people", "It depends on heaven", "If there is life, there is hope")It depends on people As long as there is success, there is hope in life##3##4comma Intervalprint ("It depends on people")If you plan things in people, you will succeed in heaven

4. Print() line break

The "end" parameter of the print() function specifies what symbol the print() function uses to indicate the end after printing the content. The default value is "\n" , indicating line break, that is, the print() function will automatically wrap the line after printing the specified content.

We can use other symbols to indicate the completion of print() output printing through the definition of the "end" parameter. For example: the "end" parameter of the print() function is specified as "|", that is, the print() function outputs "|" every time the output is completed.

Method

Code

Run result

##1

Put spaces directly in the quotation marks, there is no limit to the number of spaces

print("Planning depends on people, success depends on God, if there is life, there is hope")

Things depend on people, success depends on God. Where there is life, there is hope









Use a comma at the end of multiple lines

print ("It's up to people to make things happen",)
print ("It's up to heaven")

It's up to people to make things happen, it's up to heaven
(2 There is a space between the strings)





When printing two or more adjacent lines,

is not used

print("It depends on people"""It depends on heaven")

print ("It depends on God")

print ("It depends on people") In the sky")

If you plan things in people, you will succeed in heaven





#5

No spaces between strings

print ("It depends on people" "It depends on God")

It’s up to people to make things happen

(There is no space between the two strings)

##Run resultThere is life##No line breaks after printing, Use the end parameter to set the ending symbol you want Code##Operation resultscodeprint("Everything depends on God", end ="|")Operation results##1 2 3 4 5#5. The separator sep

Force newline

##Code

print("There is life\nThere is hope")

There is hope


print("It depends on the person", end =" ")
print("Success depends on God", end =" ")

print("If there is life, there is hope", end =" ")

If you plan for things to happen, it depends on God. If you have life, you will have hope.



print("It depends on the person" ,end ="|")

print("If there is life, there is hope", end ="|")

It’s up to people to make things happen|It’s up to God to make things happen|Where there is life there is hope|



##Code
for x in range(0, 6):

print(x, end=' ')
for x in range(0, 6):

print(x , end=',')

Run result

0 1 2 3 4 5 0,1,2,3,4,5,



##Code

for x in range(1, 6):

print( x, end=' ')

print()

for x in range(1, 6):

print(x, end=',')

print()

Run result

1,2,3,4,5,



Use the sep parameter to constrain the number of print brackets Separator between items Code##Operation results

print("It depends on the person", "Everything depends on God", "Where there is life, there is hope", sep ="&")

Planning is up to people & success is up to Heaven & as long as there is life, there is hope



#Code
print("www", "csdn", "net", sep=".")

Run results
www.csdn.net

6. Tab character\t

##Codefor i in range (1, 11):Running result1 2 3 4name = 'Adversity awake'print(name.title() " once said" ": " '\n\t"' saying '"')#Code##Run result##Codeprint("Student ID\t\tName\t\t\t\t\tSubject\t\tScore") print("100000102\tCameron Cameron\t\t\tChinese\t\t85")Run resultprint("%-10s\t %-30s\t %-10s\t %-10s"%("Student Number","Name"," Subject","score")) print("%-10s\t %-32s\t %-10s\t %-12s"%("100000101","Avatar","Chinese","80" )) print("%-10s\t %-26s\t %-10s\t %-12s"%("100000103","Monica Belluca Melon","Chinese","85 "))

Tab character\t controls the horizontal spacing. It functions like the tab key and controls the spacing distance when printing output

\t means empty 8 characters,
If the element occupies less than 8 characters, each column can be perfectly aligned, and everyone is happy;
If the character element occupies more than or equal to 8 characters, the alignment will appear Deviation, you can insert N pieces of \t to join them together, so that the elements can be aligned

or use formatted output. For details, please see the example

Code

print("You must try your best if you can't do what you want\t")

# #Running result

If you can’t do what you want, you must try your best



print(i,' \t',i*2,'\t',i*3,'\t',i*4)

2 4 6 8

##3 6 9 12

##4 8 12 16

5 10 15 20

6 12 18 24

##7 14 21 28

8 16 24 32

9 18 27 36

10 20 30 40


Code

saying="Man proposes, god disposes Man proposes, God disposes"

Running result

Adversity Awake once said:

“Man proposes, god disposes Man proposes, God disposes.”





#Error print() effect distance:

print("Student ID \tName\tSubject\tScore")

print("100000101\tAvatar\tChinese\t80")
print("100000102\tCameron Cameron\tChinese\t85")
print("100000103\tMonica Bellu Cameron\tChinese\t85")

# Alignment deviation



print(" 100000101\tAvatar\t\t\t\t\tChinese\t\t80") print("100000103\tMonica Bellu Cameron\t\tChinese\t\t85")


#Use multiple tabs and keep the alignment intact



##Code
print("%-10s\t %-30s\t %-10s\t %-12s"%("100000102","Cameron Cameron","中文","82") )


Running result
#Alignment intact

Extra: Sometimes you need to align output, you can also use format() to achieve this:

11.2
Code

products=[["iphone",6888],["MacPro",14800],["coffee",32],["abc",2499],["Book",60],["Nike",699 ],["MacPro",45600],["coffee",432],["abc",244499],["Book",6230],["Nike",61299],["MacPro",14800], ["coffee",32],["abc",2499],["Book",60],["Nike",699]]

print("-"*10 "Product List" " -"*10)

i=0

for product in products:

print('{:a55ad3b1095b33dd21834310bf418bdd | ? | @ | A | B | C | D | E | F | G | H | I
| J | K | L | M | N | O | P | Q | R | S | T | U | V | W | [ | \ | ]
| ^ | _ | ` | a | b | c | 0b10



Multiplication table

Codefor i in range (1, 10):Run result1 *1=1##

11.3 Print solid diamond

Multiplication table

for j in range(1, i 1):

print("{}*{}={}".format(j, i, i* j), end=" ")

print()

1*2=2 2*2=4

1*3=3 2*3=6 3*3=9

1*4 =4 2*4=8 3*4=12 4*4=16

1*5=5 2*5=10 3*5=15 4*5=20 5*5=25

1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36

1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49

1*8=8 2*8=16 3*8=24 4*8= 32 5*8=40 6*8=48 7*8=56 8*8=64

1*9=9 2*9=18 3*9=27 4*9=36 5*9 =45 6*9=54 7*9=63 8*9=72 9*9=81



##n=5Run result *#11.4 Print hollow diamond

##Print solid diamond

Code

for i in range(1,n 1):

print(" "*(n-i) "*"*(2*i-1))

for i in range(1,n):

print(" "*i "*"*( 2*(n-i)-1))

** *

*****

*******

**********

**** ***

*****

***

*



Print hollow diamond##Codeprint(" "*(n-1) "*")operation result * *

n=5

for i in range(1, n):

print(" "*(n-1-i) "*" " "*(2*i-1) "*")

for i in range(1, n-1):

print(" "*i "*" " "*((n-1-i)*2-1) "*")

print(" "*(n-1) "*")

*

* *

* * *

* * *

* *

* *

* *

*

*



11.5 Print hollow triangle

#11.6

##Print hollow triangle

Code

n=5

print(" "*(n-1) "*")

for i in range(2, n):

print(" "*(n-i) "*" " "*(2*(i-1)-1) "*")

print("* "*n)

Run result

*

* *

* * *

* * *

* * * * *



Print solid triangle

Coden =5Run result *#

11.7 Print side triangle (6 types)

Print solid triangle

m = 8

for i in range(0, n):

for j in range(0, m):

print (end=" ")

m = m - 1

for j in range(0, i 1):

print("* ", end=' ' )

print(" ")

* * *

* * * *

* * * *

* * * * *



##Run results

##Print side triangle 1

Code

Method 1:

i = 5

while 0 779b2cdc89fc5712d25038f46dc906d9k:

continue

print(tx,end="")

◆◆◆◆◆
◆◆◆◆

◆◆◆

◆◆



#

Print side triangle 2

Code

Method 1:

i = 1

while i 668ab991629127ae6bee9bedfee51710=-1.6:

    x = -3.0

    while xa473f859a50417eaa03b49f0d52b716b-2.4 and x9ef92a81916094aa71c615393ba0e6d8-1) or (((x2a6b48f23fac65a4b48603d108a15bbe2.2)or(x>3.4 and x874ae40d451b467a697fe1b1258fb083-1 and yc19684c0ee70f22f29898b45433e8ff6-1 and y9b2a6b50a1bd86992bf61a71df0972772.2):

            print(' ',end="")

        else:

            print('*',end="")

        x = 0.1

    print()

    time.sleep(0.25)

    y -= 0.2


import time

y = 2.5

while y>=-1.6:

    x = -3.0

    while xa473f859a50417eaa03b49f0d52b716b-2.4 and x9ef92a81916094aa71c615393ba0e6d8-1) or (((x2a6b48f23fac65a4b48603d108a15bbe2.2)or(x>3.4 and x874ae40d451b467a697fe1b1258fb083-1 and yc19684c0ee70f22f29898b45433e8ff6-1 and y9b2a6b50a1bd86992bf61a71df0972772.2):

            print('*',end="")

        else:

            print(' ',end="")

        x = 0.1

    print()

    time.sleep(0.25)

    y -= 0.2



11.11 From Dear, I love you forever! Five words output five hearts

import time

Output five hearts, respectively from Dear I love you forever! Filled with five words.






sentence = "Dear, I love you forever!"

for char in sentence.split( ):

allChar = []

for y in range(12, -12, -1):

lst = []

lst_con = ''

for x in range(-30, 30):

formula = ((x*0.05)**2 (y*0.1)**2-1)**3 -(x*0.05)**2*(y*0.1)**3

if formula 241da085dc867e1d878ba39a922b29be>Set File Encoding>>Unicode>>Unicode(UTF -8)

 3.If you use visual studio to compile and write python code,

 Python programming under visual studio 2022, an error will be reported: SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte

 Solution:

Save the Visual studio file Encoding changed to UTF-8:

##---->Unicode (UTF-8 with signature) - code page 65001

For other versions of visual studio, select "Advanced Save Options" in the file menu option

---->Unicode (UTF-8 with signature)- Code page 65001

Set the project character set to utf-8, select the project----right-click----Properties----add character set encoding

Visual Studio Community 2022 - UTF-8 codec issue #6784, please refer to reading:

https://github.com/microsoft /PTVS/issues/6784

## Digression: When making charts with matplotlib (pyplot), the title and axis The Chinese display will be abnormal and a small box will appear, which cannot be displayed normally. In this case, just add the following code to the header of the file:

#-*- coding: UTF-8 -*-

import matplotlib.pyplot as plt

import matplotlib as mpl

mpl.rcParams["font.sans-serif"]=["SimHei"]

mpl.rcParams["axes.unicode_minus"]=False

13. Print() writes to the file

Write the print content to the file.

Sometimes, we will encounter situations where we want to print content not only on the screen, but also saved in a file. Then, we can try to write the print content to the file as follows:

Create the test.py file and enter:

#

Write Input file

code

# coding=utf-8

print("Hello, World!", file=open('file.txt', 'w'))


##Running result

After running, a file.txt file appears in the directory where the test.py file is located. Open the file.txt file and you will find that the content inside is:

Hello, World!

means that our print() writes the file successfully.




#【Related recommendations:

Write file

Code

for i in range (1, 11):

print(i,'\t',i*2,'\t',i*3,'\t',i*4,end='\ n',file=open('file.txt',mode ='a',encoding='utf-8'), flush=False)

Running results

After running, open the file.txt file and you will find that the content inside is:


##1 2 3 4

2 4 6 8

3 6 9 12

4 8 12 16

5 10 15 20

6 12 18 24

7 14 21 28

8 16 24 32

9 18 27 36

10 20 30 40


Indicates that our print() writes the file successfully.




Python3 video tutorial


The above is the detailed content of Detailed explanation of examples of usage of Print() function in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete