Python string formatting

Source: Internet
Author: User

The string formatting operator (%) applies only to string types, very similar to the string formatting of the printf () function in C, and even uses the same symbols, with percent sign (%), and supports all printf () format operations. The syntax is as follows:
Format_String% String_to_convert
Format_String is a format-tagged string, in the form "%cdoe"; String_to_convert is a string to be formatted, and if it is more than two, it needs to be enclosed in parentheses.

Td>%g/%g
string formatting symbols
formatting symbols description
% c converted to a character (ASCII value, or a string of one length)
%r takes precedence over string conversions with the repr () function (Python2.0 new)
%s takes precedence over string conversions with the str () function
%d/%i   go to signed decimal number
%u turns unsigned decimal number
%o turns unsigned octal number
%x /%x (Unsigned) turns to unsigned hexadecimal number (x/x represents large
lowercase for converted hexadecimal characters)
%e/%e to scientific notation (e/e control output e/e)
%f/%f turn into floating-point numbers (fractional parts naturally truncated)
%e and%f/%e and%f abbreviations
%% output%
>>> #打印字符串 >>> print (' My name is%s '% ' Rusky ') My name is rusky>>> #打印整数 >>> print (' He i  S%d years old '% (in)) He is years old>>> #打印浮点数 >>> print (' His height is%f M '% (1.78)) He height is 1.780000 m>>> print (' His height is%.2f M '% (1.78)) He height is 1.78 m>>> #指定占位符宽度 >>> print ( ' name:%10s age:%8d height:%8.2f '% (' Rusky ', 26,1.78)) Name:     Rusky Age:      Height:    1.78>>> # Specify placeholder width-left alignment >>> print (' name:%-10s age:%-8d height:%-8.2f '% (' Rusky ', 26,1.78)) Name:rusky      age:26       height:1.78    

  

Python string formatting

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.