0 Fundamentals python-7.6 String formatting expressions

Source: Internet
Author: User

String formatting agrees to run multiple specific types of substitutions on a string in a single step

Especially when prompted by the user, formatting is very convenient

Implementation method:

1. Formatting expressions, similar to C-voice printf

In an expression, we use the% binary operator

>>> print (' This was%d%s bird '% (1, ' dead ')) This is 1 dead bird

Give the example above (note that the% we are talking about is the same as the one in the middle of the string and the tuple)

Place a string on the left side of%. One or more embedded objects with a% start in the string are placed inside

Put one (or more) on the right of%. Embedded tuples where the objects are inserted into the left translation target location


When multiple objects are inserted. They need to be put into a tuple.


2. Advanced Format expressions

String Formatting code list

Code Significance
S String (or whatever object)
R S, but with repr instead of STR
C Character
D Decimal integer
I Integer
U No number integer
O Eight-binary integers
X hexadecimal integer
X X. But print uppercase
E Floating point Index
E E, but print uppercase
F Floating point Decimal
F Floating point Decimal
G Floating point E or F
G Floating point E or F
% constant

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

Sample Example

>>> x=1234>>> res= ' integers:...%d...%-6d...%06d '% (x,x,x) >>> res ' integers: ... 1234...1234  

%e,%f,%g There are differences in the printing of floating-point numbers


3. Dictionary-based formatting expressions


To put it bluntly is to give each alternate location a name, so the code looks clearer


Here we are, thank you.

------------------------------------------------------------------

Click the jump 0 Basic python-folder


0 Fundamentals python-7.6 String formatting expressions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.