Python Learning string formatting

Source: Internet
Author: User

Table 3.1. String Formatting code

format Description
%% Percent percent sign%
%c Characters and their ASCII code
%s String
%d Signed integer (decimal)
%u unsigned integer (decimal)
%o unsigned integer (octal)
%x unsigned integer (hexadecimal)
%x unsigned integer (16 uppercase characters)
%e Floating-point numbers (scientific notation)
%E Floating-point numbers (scientific notation, E instead of e)
%f Floating point number (with decimal point symbol)
%g Floating-point numbers (%e or%f depending on the size of the value)
%G Floating-point numbers (similar to%g)
%p Pointer (memory address of the value printed in hexadecimal)
%n Stores the number of output characters into the next variable in the parameter list
#a tuple is used to pass multiple values to a template, each of which corresponds to a format character. A ="I ' m%s. I ' m%d year old"% ('Vamei', 99)Print(a)#You can also use dictionaries to pass real valuesPrint("I ' m% (name) s. I ' m% (age) D- old"% {'name':'Vamei',' Age': 99})

The format can be further controlled in the following ways:

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

(name) is named

Flags can have +,-, ' or 0. + Indicates right alignment. -Indicates left alignment. ' is a space that fills a space on the left side of a positive number to align with a negative number. 0 means using 0 padding.

Width indicates display widths

Precision indicates the precision after the decimal point

Like what:

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

The width above, precision is two integers. We can use * to dynamically substitute these two quantities. Like what:

Print ("%.*f"% (4, 1.2))

Python actually replaces * with 4来. So the actual template is "%.4f".

The built-in% operator in Python can be used to format string operations and control the rendering format of strings. There are other ways to format strings in Python, but the use of the% operator is most convenient.

Reference:

Vamei

Python Learning string formatting

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.