pythn print output format:% s% d and

pythn print formatted output.

 

% r used for debug better, because it displays the original data variables (raw data), and the other symbol
number is used to display output to the user.

 

1. Print string

print ("His name is %s"%("Aviad"))
效果:

2. Print integer

print ("He is %d years old"%(25))
效果:

 

3. Print a float

print ("His height is %f m"%(1.83))
效果:

 

4. Print a float (number of decimal places specified reservations)

print ("His height is %.2f m"%(1.83))
效果:

 

The specified width placeholder

print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))
效果:

 

6. Specify placeholder width (left)

print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))
效果:

 

7. Specify a placeholder (0 can only be used when a placeholder?)

print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))
效果:

 

8. scientific notation

format (0.0015, '2e.' )
Effects:

 

  We also may use a dictionary to deliver real value. as follows:

print ("I'm %(c)s. I have %(l)d yuan." % {'c':'hungry','l':22})
调试输出:
I'm hungry. I have 22 yuan.


Formatter

Specifier placeholder for a true value, and controls the display format. Specifier may contain a type code for controlling the display type as follows:

% S string (using str () display)

% R string (using the repr () display)

% C single character

% B binary integer

% D decimal integer

% I decimal integer

% O octal integer

% X hexadecimal integer

% E index (written as a substrate e)

% E index (base written as E)

% F float

% F float, on the same

% G exponent (e) or floating-point (the length of the display)

% G index (E) or float (the length of the display)

 

%% character "%"

 

You can use the following manner, to further control the format:

%[(name)][flags][width].[precision]typecode

(Name) is named

flags can be +, -, '' or 0. + Represents a right alignment. - for left-aligned. '' Is a space, a space to fill in the left represents a positive number so as to align with the negative. 0 0 fill indication.

width represents the width of the display

It represents a decimal precision accuracy

 

such as:

print("%+10x" % 10)
print("%04d" % 5)
print("%6.3f" % 2.3)
 

The above width, precision of two integers. We can use * to the dynamic generation of these two quantities. such as:

Print ( "%. * F"% (4, 1.2))
the Python actually be replaced with 4 *. So the actual template "% .4f".

 

to sum up

Python built% operator can be used to format string operations, the presentation format control character string. There are other ways in Python format string, the operator using the% is the most convenient.
---------------------
Author: SuperCreators
Source: CSDN
Original: https: //blog.csdn.net/SuperCreators/article/details/81393977
Disclaimer: This article as a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/huigebj/p/11238280.html