Detailed explanation of examples of usage of Print() function in Python
WBOY
Release: 2022-11-14 20:28:58
forward
6585 people have browsed it
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.
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 (""" """)
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! '
#Triple quoted
A pair of triple quotes, quoting multiple lines of text
Multilinetext="""
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,
must do as they can.
If you can’t do what you want,
you must try your best.
3. How to use spaces in print()
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
#2
Use commas between two adjacent items Interval
print("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
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)
##4
When printing two or more adjacent lines,
is not used
comma Interval
print("It depends on people"""It depends on heaven")
print ("It depends on people")
print ("It depends on God")
print ("It depends on people") In the sky")
If you plan things in people, you will succeed in heaven
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)
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.
Force newline
##Code
print("There is life\nThere is hope")
##Run result
There is life
There is hope
##No line breaks after printing, Use the end parameter to set the ending symbol you want
Code
print("It depends on the person", end =" ")
print("Success depends on God", end =" ")print("If there is life, there is hope", end =" ")
##Operation results
If you plan for things to happen, it depends on God. If you have life, you will have hope.
code
print("It depends on the person" ,end ="|")
print("Everything depends on God", end ="|")
print("If there is life, there is hope", end ="|")
Operation results
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
1,2,3,4,5,
#5. The separator sep
Use the sep parameter to constrain the number of print brackets Separator between items
Code
print("It depends on the person", "Everything depends on God", "Where there is life, there is hope", sep ="&")
##Operation results
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
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
##Code
for i in range (1, 11):
print(i,' \t',i*2,'\t',i*3,'\t',i*4)
Running result
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 288 16 24 329 18 27 3610 20 30 40
Code
name = 'Adversity awake'
saying="Man proposes, god disposes Man proposes, God disposes"
print(name.title() " once said" ": " '\n\t"' saying '"')
Running result
Adversity Awake once said:
“Man proposes, god disposes Man proposes, God disposes.”
#Code
#Error print() effect distance: print("Student ID \tName\tSubject\tScore")
If there is a mathematical expression in the brackets after print, the printed result will be the result of the final operation of the expression
Print prints the value of the expression
Code
Print(1 2 3 4 5)
Run results
15
##Code
##print(8/1)
Running results
8.0
##Code
print(2*4)
Run results
8
##Code
print(18-10)
Run Result
8
##Code
print(2 6)
##Run result
8
8. Print out backslashes\
Print backslashes, put 2 backslashes together
Code
Print("If you can't do what you want\\you must do your best")
Operation results
If you can’t do what you want, you must try your best
#
9. Output of print() variables
No matter what type of data, including but not limited to: numerical type, Boolean type, list variable, dictionary variable...all can be passed through print() Direct output.
Output of print() variable
Code
#Output numeric variable
num = 91682
print(num)
Running result
91682
##Code
#Output string variablename = 'Sober in adversity'print(name)
Running results
Sobering up in adversity
Code
#Output list variablelist = [1,2, 3,4,5,'a','b','c']print(list)
Running result
[1, 2, 3, 4, 5, 'a', 'b', 'c']
##Code
#Output tuple variable
tuple = (1,2,3,4,5,'a','b','c')
print(tuple)
Run results
(1, 2, 3, 4, 5, 'a', 'b', 'c')
##Code
#Output dictionary variable
dict ={'a':1, 'b':2,'c':3}print(dict)
operation result
{'a': 1, 'b': 2, 'c': 3}
10. Formatted output of print() data
Insert into the string
Code
Run result
1
String variable
name = "Sober in adversity"
print("My name is %s " % name)
My name is Awake in Adversity
##2
Integer variable
age = 100print("My age is %d"%(age) "years old")
My age He is 100 years old
##3
Decimal variable
i = 2670.5
print("The number is %f" %i)
The number is 2670.500000
% dot (.) followed by the field width;
% dot (.) Followed by the precision value; in the field width, the decimal point also occupies one place
i = 2.67145573
print("8-bit reserved field Width %(i))
8-bit reserved field width 2.671456
##i = 2.67145573
print("The output with two decimal places is %.2f"%(i))The output with two decimal places is 2.67
#i= 2.6714563467print( "a" ' .3f'%i)print("a" '%f'%i)
a 2.671a2 .671456
(The precision is 3, so only .671 is displayed, and the specified width is 10, so 5 spaces are added to the left to reach a field width of 10 digits. In the field width, the decimal point also occupies one digit)
#4
s='Sober in adversity'
x=len( s)
print('The length of %s's name is %d' %(s,x))
The length of the sober name in adversity is 4
Format output
Code
Run result
%s
Output a string, characters The string is displayed using str()
i= 2.6714563467
print('%s'%i)
2.6714563467
#%r
Display of string (repr())
print('%r '%repr(set([1,1,2,3])))
##'{1, 2, 3}'
#% c
Output a single character
print('%c'�)
Z
#%e, %E
Index (base e)
k= 2671.4563467284
print('%e'%k)
print('%E'%k)
##2.671456e 032.671456E 03
#%b
Binary integer
print(bin(50))
0b110010
#%hd, %d, %ld
Output integers of types short, int, and long in decimal and signed form
print('%d'P)
50
%hu, %u, %lu
Output integers of types short, int, and long in decimal and unsigned form
print('%u'P
50
#%ho, %o, %lo
In octal, without prefix, Outputs integers of types short, int, and long in unsigned form
print('%o'P)
62
#%#ho, %#o, %#lo
Output short in octal, prefixed, unsigned form , int, long type integer
##print('%#o'P)
0o62
#%hx, %x, %lx,
%hX, %X, %lX
In hexadecimal , output short, int, long type integers in unprefixed and unsigned form. If x is lowercase, then the output hexadecimal numbers are also lowercase; if X is uppercase, then the output hexadecimal numbers are also uppercase.
print('%x'P)
32
#%#hx、%#x、%#lx、%#hX、%#X、%#lX
# Outputs integers of types short, int, and long in hexadecimal, prefixed, and unsigned form. If x is lowercase, the output hexadecimal numbers and prefix are both lowercase; if X is uppercase, the output hexadecimal numbers and prefix are both uppercase.
print('%#x'P)
print('%#X'P)
0x32
0X32
#%f, %lf, %F
Output floating point numbers of type float and double in decimal form
i= 2.6714563467
print('%f'%i)2.67146
# %g, %lg,
%G, %lG
outputs float or double type decimals in the shorter form of decimal or exponent, and the decimal part is No extra 0's are added at the end. If g is lowercase, e is also lowercase when output in exponential form; if G is uppercase, E is also uppercase when output in exponential form.
n=5print(" "*(n-1) "*") for i in range(2, n): print(" "*(n-i) "*" " "*(2*(i-1)-1) "*")print("* "*n)
Run result
* * * * * * * * ** * * * *
#11.6
Print solid triangle
Print solid triangle
Code
n =5
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 result
*
* * *
* * * *
* * * *
* * * * *
#
11.7 Print side triangle (6 types)
##Print side triangle 1
Code
Method 1: i = 5while 0 < i < ;= 5: j = 1 while j <= i: print("* ", end = '') j = 1 print(" ")
i -= 1
## Method 2:
for i in range(0,5):
tx="◆"
print()
for k in range( 0,5):
if i>k:
continue
print(tx,end="")
##Run results
◆◆◆◆◆
◆◆◆◆◆◆◆ ◆◆◆
#
Print side triangle 2
Code
Method 1:
i = 1
while i <= 5:
j = 1
while j <= i:
.
Method 2:
n = 5
print('\n'.join('◆' * i for i in range(1, n 1)))
Run results
##◆
◆◆
◆◆◆
◆◆◆◆
◆◆◆◆◆
Print side triangle 3
Code
for i in range(0,5): tx='◆'
tx1=' '
print() for j in range(0,5):
print(tx if i<=j else tx1,end="") Run results
##◆◆◆◆◆
◆◆◆◆
◆◆◆
◆◆
◆
#
Print triangle 4
code
for i in range(0,5):
tx='◆'
tx1=' '
print()
for j in range( 0,5):
Print(tx if i<=j else tx1,end="")
Run result
◆◆◆◆◆
◆◆◆◆
◆◆◆
◆◆
◆
#Print triangle 5
Code
l= 5for i in range(l): for j in range(i): print(end=' ') for k in range(2*(l-i)-1): print(end='◆') print()
Run results
##◆◆◆◆◆◆◆◆◆
◆◆◆◆◆◆◆
◆◆◆◆◆
◆◆◆
◆
##
Print triangle 6
Code
i = 1
while i <= 9:
if i <= 5:
print('◆ '*i)
else:
Print ('◆'*(10 -i))
i = 1
#◆
◆ ◆◆ ◆ ◆◆ ◆ ◆ ◆◆ ◆ ◆ ◆ ◆◆ ◆ ◆ ◆◆ ◆ ◆◆ ◆◆
#11.8 Printing parallelogram
Print parallelogram
Code
l = 5
for i in range(l):
for j in range(l-i):
print(end=' ')
for k in range(l):
print(end='◆')
print()
Running results
## ◆◆◆◆◆ ◆◆◆◆◆
◆◆◆◆◆ ◆◆◆ ◆◆ ◆◆◆◆◆
##
11.9 Use the letters word love to print a heart shape
Use the letters word love to print a heart shape
Code
print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ( (x*0.05)**2 (y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))
Running result
#
11.10 用字符输出 I ❤ U (2款效果)
用字符输出 I 爱 U (2款效果)
import time
y = 2.5
while y>=-1.6:
x = -3.0
while x<=4.0:
if (x*x y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.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 x<=4.0:
if (x*x y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.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
Output five hearts, respectively from Dear I love you forever! Filled with five words.
import time
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 <= 0:
lst_con = char[(x) % len(char)]
else:
lst_con = ' '
lst.append(lst_con)
allChar = lst
print('\n '.join(allChar))
time.sleep(1)
##
12. Print() Chinese input displays garbled characters
If there are Chinese characters in the code, python will report an error when running, and the Chinese cannot be input normally in python, garbled characters, etc.:
Compilation tip: SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x*** in position 0: ...
Mainly caused by encoding problems.
Affected by different development systems and environments, the solutions will be different, but generally the solution can be solved by following the following methods. If necessary, please try the solution that suits your own system: (Remember, the following You don’t need to add all the methods to the python file, just choose one or two of them to try, which can solve the problem)
In the first line of your python file (.py)
1. Add
16d72c9aa3ac3878a4b43bd6a3af54b5
When developing python, please note:
1. If you use pycharm Compile and write python code, pycharm will automatically save it in UTF-8 format by default. If you have modified it accidentally, please right-click on the pycharm work interface-File-Encoding-select UTF-8 encoding----reload- ----reload anyway. If that still doesn't work, try changing the path to all English.
2. If you use other compilation and writing code tools, please click
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:
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.
Indicates that our print() writes the file successfully.
#【Related recommendations:
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!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn