6 the format () function in Python

Source: Internet
Author: User
Tags print print string format vars
string Format-format ()

Reprint please indicate the source (http://blog.csdn.net/lis_12/article/details/52712994). Common formatting methods

(%s%d) generates a formatted string where S is a formatted string and D is a decimal number;

The format string contains two parts: the normal character and the conversion specifier (see the table below).

Replaces the conversion specifier with a string of elements in a tuple or map;

* * If D is a tuple, it must match the number of conversion specifiers in S;
If D is dict, each conversion specifier must be associated with a valid key name in Dict. * *

conversion specifier, starting with% output Format
D,i Decimal
U Unsigned number
O Octal
X hexadecimal or Long integer
X Hexadecimal
F,e,e Floating point numbers
G,g Used when index is less than-4
S String or any object, a string generated with Str
R Strings generated by the same repr

3. between the% character and the converted character, the following modifiers can appear, and can only appear in the following order , a key in parentheses, which is used to get the value of the key from the dict, and if no key exists, throws an exception; One or more of the following:
-The left alignment flag, which defaults to the right alignment; +, indicating that the sign should contain a number; 0, with 0来 filling; A number that specifies the minimum automatic width. The converted value is printed in a string of at least this width, and the left padding to the full character Decuan (padding on the right if the-flag is specified);(if the length of the string itself is greater than the specified width, this width is useless). A decimal points for dividing the field width by precision; A number that specifies the maximum number of characters in the string to be printed, the number of digits after the decimal point in the floating-point number, or the minimum digits of the integer;

The

* Replaces numbers in fields of any width. If present, the width will be read from the next item in the tuple; (A little dizzy--it's easy to understand with the following code)

#!/usr/bin/python #-*-Coding:utf-8-*-#1 a = {"name": ' Ljs ', "age":, ' weight ': "Print"% (name) s% (age) d (weigh t) D; "


%a #ljs 22 75; #将已经定义的变量扩展到字符串中 name = ' Ljs ' age = Weight = + R = '% (name) s% (age) d (weight) D; "
%vars () print R #ljs 22 75; The print VARs () #vars () function contains a dictionary of all variables defined at this time #2 and 3 a = ' abc ' b = c = -100 print '%d '% (a,b) #error print " %10s; " %a # ABC; minimum width is 10, width is less than 10, default is right, add space to left until width is ten print "%-10s" %a #abc Minimum width of 10, width is insufficient 10,-for left alignment flag, add space to right until width of print "%+10s;" %a # ABC; string has no symbol, so flag + does not function print "%010s" %a # ABC; not numbers, no padding 0, so flag 0 doesn't work print "%10d." %B # 100, minimum width of 10, less than 10 width, default to right, add space to left until width of print "%-10d;" %b #100 Minimum width of 10, width is insufficient 10,-for left alignment flag, add space to right until width of print "%+10d;" %b # +100, print out the symbol printed "%+10d;" %c #-100; print out a sign printed "%+010D;" %b #+000000100 padding 0 to width #4 5 a = 1.23456 print "%f"%a #1.234560; Print print "%3f"%a #1.234560; The minimum width is 3, ButThe length has exceeded the 3,so normal print "%10f"%a # 1.234560; The minimum width is 10, the width is less than 10, the default is right-aligned, and the left space is added to the width of the print "%.3f"%a #1.235; The number after the decimal point is fine. , 3-bit print "%.10f"%a #1.2345600000 after the decimal point, less than 10 digits, 0 to digits #6 a = 123456.7890123456 print "%*.*F;" 15,5,a) # 123456.78901; The first * is the minimum width, the second * is the precision print "%-*.*f" after the decimal point ( 15,5,a) #123456.78901;
Advanced String Formatting

The format () function of the string that collects any collection of positional and keyword parameters and replaces placeholders in the string with their values;

placeholders with the form {n} (n as integers) will be replaced by the nth parameter of the format () method;

placeholders with the form {name} will be replaced by the parameter named name;

If you want to use the format () output {xx}, you must use {{XX}}}, otherwise you will be unable to find the corresponding parameter value error;

You can specify a format specifier to control the output more precisely.

Add optional format specifier symbols to each placeholder, such as {name:format_spec}. This specifier specifies the column width, decimal position, and alignment.

General format [Fill,align,sign,0,width,.precision,type], each of which is optional. fill: is an optional padding character used to fill blanks , default to spaces; Align, Alignment. <,>,^ is left, right, center aligned , default right-aligned , sign, and values are:
+, all digital signatures should be added to the symbol; -, default value, only sign with negative sign; Spaces, preceded by a positive number plus a space; 0, plus 0 in front of the width to fill the blank before the value with 0来; width, breadth;. Precision, the number of digits of precision; Type, data type, such as D (Integer), S (string), etc.

In some cases, you might just want to format the object's str () or repr () to indicate that you need to bypass the __format__ () method. To do this, you can add a!r or!s specifier before the format specifier, if you do not see the following code.

#!/usr/bin/python #-*-Coding:utf-8-*-' help Str.format (...)
    S.format (*args, **kwargs)-> string return a formatted version of S, using the substitutions from args and Kwargs.
The substitutions are identified by braces (' {' and '} '). ' print ' {{a}} '. Format () #{a} print ' {a} '. Format () #error, there is no parameter print "{A}" for a-{ b} ". Format (a = 100,b =) #100 -200 print" {0},{0} ". Format (11,22) #11, one print" {0},{0},{1},{2} ". Format (11,22 , 33) # 11,11,22,33 The number of brackets inside represents the first few parameters print "{0:3d},{1:4s},{1:5s},{2}". Format (One, "a",) # ' 11,a, A, ' print ' {0:=&G T;+011.3F}; ". Format (12.12345) #====+12.123 with = to fill, right alignment, because already filled with =, 0 invalid, width 11, decimal precision after precision 3, type is floating point print "{0:>+011.3f};".

Format (12.12345) #0000 +12.123; A = "test" print "{0:^10}". Format (a) #test print "{0!s:^10}". Format (a) #test print "{0!r:^10}" . Format (a) # ' test ' #通过下标也行 a=[1,2] print ' {0[0]},{0[1]} '. foRmat (a) #1, 2 #对象属性 class Test (object): Def __init__ (self,name,age): Self.name,self.age = Name,age
        def __str__ (self): Return ' This boy was {self.name},is {self.age} old '. Format (self=self) def str (self): Return self.__str__ () a = Test (' Lilei ',.) print str (a) #This boy is lilei,is an old print a.str () #This Boy is Lilei,is #format函数单独使用 format (' abc ', ' 10s ') # ' ABC '

In summary, consider the parameters in format () as a normal parameter, which can be used in the string (s) in the S.format ()!!!

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.