Python: Format

Source: Internet
Author: User
Sender: n23 (23rd), email area: Python
Title: ZZ what's new in Python 2.6 (7)-pep 3101: improved words
Mail station: shuimu community (Tue Oct 7 17:20:45 2008), mail

Pep 3101: improved string formatting

In Python 3.0, the % operator is enhanced by a stronger format () method. Support for Str. Format () has been reversely transplanted to Python 2.6

In 2.6, both the 8-bit string and the Unicode string have a format () method. This method treats the string as a template and uses the input parameters for formatting. The template used for formatting uses braces ({,}) as special characters.

# Substitute positional argument 0 into the string.
"User ID: {0}". Format ("root")-> "User ID: Root"

# Use the named keyword arguments
'User ID: {uid} Last seen: {last_login} '. Format (
Uid = 'root ',
Last_login = '5 Mar 2008 ')->
'User ID: Root last seen: 5 Mar 2008'

You can write the braces twice to escape them.

Format ("Empty dict: {{}}")-> "Empty dict :{}"

The field name can be an integer to indicate the parameter location. Such as {0} and {1. It can also be the parameter name. You can use a combination of fields to read the key values of attributes or dictionaries.

Import sys
'Platform: {0. Platform} \ npython version: {0. Version} '. Format (sys)->
'Platform: Darwin \ n
Python version: 2.6a1 + (trunk: 61261 M, Mar 5 2008, 20:29:41) \ n
[GCC 4.0.1 (Apple Computer, Inc. Build 5367)]'

Import mimetypes
'Content-type: Using 02.16.mp4]} '. Format (mimetypes. types_map)->
'Content-type: Video/mp4'

The value of the primary key. A string starting with an integer is converted into an integer. You cannot write complex expressions in formatted strings.

At this point, we have demonstrated how to replace the specified field. You can also add a colon after the formatting indicator to perform exact formatting. For example:

# Field 0: Left justify, pad to 15 characters
# Field 1: Right justify, pad to 6 Characters
FMt = '{0: 15 }$ {1:> 6 }'

FMT. Format ('registration', 35)->
'Registry $35'

FMT. Format ('tutorial ', 50)->
'Tutorial $50'

FMT. Format ('banquet ', 125)->
'Banquet $125'

The format indicator can be referenced through nesting.

FMt = '{0: {1 }}'

Width = 15
FMT. Format ('invoice #1234 ', width)->
'Invoice #1234'

Width = 35
FMT. Format ('invoice #1234 ', width)->
'Invoice #1234'

You can specify the alignment of the desired string.
Effect Characters:
<(Default) left alignment
> Right alignment
^ Center alignment
= (Used only for numbers) after the decimal point

The format indicator can contain a display type to control the format. For example, a floating point number can be formatted in a common format or expressed by a power.

>>> '{0: g}'. Format (3.75)
'3. 75'
>>> '{ 0: e} '. Format (3.75)
'3. 752.16e + 00'

There are many display types. 2.6 contains a complete list of documents. Some examples are listed here.

'B'-binary. Outputs the number based on 2.
'C'-character. Convert the integer to the corresponding Unicode string before printing.
'D'-a decimal integer. Outputs the number based on 10.
'O'-octal. Outputs the number based on 8.
'X'-hexadecimal. The number is output based on 16, and the digits above 9 are lowercase letters.
'E'-power symbol. Print numbers in scientific notation. Use 'e' to represent the power.
'G'-General format. Output the value in fixed-point format. When the value is very large, print it in the power form.
'N'-number. When the value is an integer, it is the same as 'D', and the value is the same as that of 'g. The difference is that it inserts a digital separator according to the region settings.
'%'-Percentage. Multiply the value by 100 and print it in the fixed-point ('F') format. The value is followed by a percentage sign.

Classes and types can define a _ format _ () method to control how to format yourself. It accepts a format indicator as a parameter:

Def _ format _ (self, format_spec ):
If isinstance (format_spec, Unicode ):
Return Unicode (STR (Self ))
Else:
Return STR (Self)

There is also a built-in format () method that can be used to format a value. It calls the _ format _ () method of the type and transmits the formatted indicator as a parameter.

>>> Format (75.6564, '. 2f ')
'75. 66'

Reference

Syntax for formatting strings-reference for formatting Fields
Pep 3101-advanced string formatting
Pep is compiled by talin and implemented by Eric Smith.

From http://www.onlypython.com/post/1926/

--
As a happy person from tomorrow,
Cutting firewood, feeding horses and traveling around the world;
I have a room facing the sea,
Spring flowers bloom.
--
My blog: http://n23.appspot.com/blog/

※Source: · Shui Mu community newsmth.net · [from: 203.86.138. *]

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.