Questions about%d,%2d,%02d in the Python string

Source: Internet
Author: User

In Python, the purpose of formatting a string is achieved by using%. (This is consistent with C language)

where integers and floating-point numbers are formatted, you can specify whether to complement 0 and the number of integers and decimals.

First, introduce a concept of field width.

The width of the format output character is represented in the C-language midfield wide.

For example:

You can insert a number between "%" and a letter to indicate the maximum field width.

The%3d represents the output of 3-bit integers, not enough 3-bit right-justified.

The%9.2f represents a floating-point number with an output field width of 9, where the decimal bit is 2, the integer digit is 6, the decimal point is one, and not enough 9-bit right-aligned. (Note: The number before the decimal point must be greater than the number after the decimal point.) The value before the decimal point specifies the total width of the printed number. If omitted (for example:. 2f), it means that the total width is unrestricted. )

The%8s represents the output of a 8-character string, which is not aligns aligned to 8 characters.

Output of%d:

 for  in range (0,10):    ...:     print('%d' %i) ...    : 0 123456789

%2d Output: (Field width is 2, right-aligned)

 for  in range (0,10):    ...:     print('%2d' % i)    ...:    1 2 3 4 5 6 7 8 9

%02d output: (Complement 0)

 for  in range (0,10):    ...:     print('%02d' %i) ...    :    .    ..:...: 00010203040506070809

Output from%.2d:

 for  in range (0,10):    ...:     print('%.2d' % i)    ...:00010203040506070809

Questions about%d,%2d,%02d in the Python string

Related Article

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.