Python Basics (2)--formatting strings __python

Source: Internet
Author: User

Python provides two formatting methods % and format. 1. Format Strings by%

The% format string of Python is similar to the printf () function in C language.

(1) format the output of a tuple.

(2) format the output of a dict.

2. Format a string by using the format

the format passes {} and: to replace%. Specifically, it is formatted by mapping (with {}) and by a format qualifier ({} with:). 2.1 Format by mapping

The mapping format method has a number of passes through the position , through the parameter , through the keyword , through the object attribute and through subscript.
(1) through the location of the format

(2) format by keyword parameter

(3) Formatting by object attributes

The specific implementation code is as follows:

Class City:
    def __init__ (self,name,year):
        self.name,self.year = Name,year
    def __str__ (self):
        return ' The city is {Self.name},today is {self.year} '. Format (self=self)

(4) The format is realized by subscript

2.2 Formatting with a format qualifier

The format qualifier mainly includes padding and alignment, precision , feed and separator , and so on.

(1) Padding and alignment
The most common are centered (^), left-aligned (<), right-aligned (>), followed by the string width.
Only single character padding is supported and padding is by default with spaces.

(2) Precision limit

(3) into the system

In Python, B, D, O, X represents binary, octal, decimal, hexadecimal, respectively.

(4) Separator
In addition, format supports the use of "," as a thousand-separator character.

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.