Python string formatting method use of the Format function

Source: Internet
Author: User
Tags time and date

Python supports format from 2.6, a new, easier-to-read string formatting method that changes from the original% mode to a new, more readable
    1. The curly braces declare {}, the parameter reference declaration before the render, and the curly brackets can use numbers to denote the ordinal of the reference parameter, or the variable name to refer directly.
    2. The variable name introduced from the format parameter,
    3. Colon:
    4. The number of character bits declaration,
    5. Declaration of a blank auto-fill character
    6. Statement of the thousand-digit point
    7. Declaration of a variable type: string s, Number D, floating point F
    8. Alignment direction Symbols < ^ >
    9. Property accessors in parentheses ?
    10. Use an exclamation point! followed by A, R, S, declares which mode to use, acsii mode, reference __repr__, or __str__
    11. Add the Magic function __format__ (self, format), you can customize the different display according to the format of the string before format, such as: ' {: xxxx} ' at this time XXXX will be passed as a parameter in the __FORMAT__ function.
A comprehensive example shows:
    1. Such as: Thousands of points, floating point numbers, padding characters, the combination of alignment use:
Enter: ' {: >18,.2f} '. Format (70305084.0) #: Colon + blank padding + right-aligned + fixed-width 18 + floating-point precision. The F-output: ' 70,305,084.00 '
    1. Complex data formatting
Input: Data = [4, 8, +, +, +] ' {d[4]} {d[5]} '. Format (d=data) output: 23 42
    1. Complex Data formatting:
Input: Class Plant (object):
Type = ' Tree '
kinds = [{' name ': ' Oak '}, {' name ': ' Maple '}]

' {P.type}: {P.kinds[0][name]} '. Format (p=plant ()) Output: Tree:oak Classification Example:
    • The curly braces declare {}, the parameter reference declaration before the render, and the curly brackets can use numbers to denote the ordinal of the reference parameter, or the variable name to refer directly.
' {{} {} '. Format (' One ', ' ' One ', ' ') ' {1} ' {0} '. Format (' One ', ' both ') OutputOne Setup
data = {' first ': ' Hodor ', ' last ': ' hodor! '}
Old
'% (first) s% (last) s '% data
New
' {first} {last} '. Format (**data)
Outputhodor hodor!
    • The variable name introduced from the format parameter,
    • Colon:, character digit declaration, blank auto-fill declaration, thousand-bit declaration, variable type declaration: string s, Number D, floating-point number F, Alignment direction symbol < ^ >
' {:. 5} '. Format (' xylophone ')
Outputxylop
' {: ^10} '. Format (' Test ')
Output Test
‘{:. {}} '. Format (' xylophone ', 7)
Outputxylopho
' {: 4d} '. Format (42)
Output 42
' {: 06.2f} '. Format (3.141592653589793)
Output003.14
' {: +d} '. Format (42)
OUTPUT+42: Enter: ' {: >18,.2f} ' using a combination of thousands of decimal points, floating-point numbers, padding characters, and alignment. Format (70305084.0) #: Colon + blank padding + right-aligned + fixed-width 18 + floating-point precision. The F-Output: ' 70, 305,084.00 '
    • Property accessors in parentheses ?
Setup
person = {' first ': ' Jean-luc ', ' last ': ' Picard '}
New
' {P[first]} {P[last]} '. Format (P=person)
Output
Setup
data = [4, 8, 15, 16, 23, 42]
New
' {D[4]} {d[5]} '. Format (d=data)
Output23 Setup
Class Plant (object):    type = ' tree '    kinds = [{' name ': ' Oak '}, {' name ': ' Maple '}]
New
' {P.type}: {P.kinds[0][name]} '. Format (P=plant ())
Outputtree:oak
    • Exclamation! Restrict access to magic functions such as __repr__:
Setup
Class Data (object):    def __str__ (self):        return ' str '    def __repr__ (self):        return ' repr '
Old
'%s%r '% (data (), data ())
New
' {0!s} {0!r} '. Format (Data ())
Outputstr repr
    • Add the Magic function __format__ (self, format), you can customize the different display according to the format of the string before format, such as: ' {: xxxx} ' at this time XXXX will be passed as a parameter in the __FORMAT__ function.
Setup
Class HAL9000 (object):    def __format__ (self, format):        if (format = = ' Open-the-pod-bay-doors '):            return "I ' m Afraid I can ' t do that. "        Return ' HAL 9000 '
New
' {: open-the-pod-bay-doors} '. Format (HAL9000 ())
Outputi ' m afraid I can ' t do.
    • Special cases of time and date:
Setup
From datetime import datetime
New
' {:%y-%m-%d%h:%m} '. Format (DateTime (2001, 2, 3, 4, 5))
output2001-02-03 04:05

Python string formatting method use of the Format function

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.