On Python string formatted output (format/printf) _python

Source: Internet
Author: User
Tags python string format string format

The Python string is formatted with the character% format 1 format 2 character% (variable 1, variable 2), and the% format represents the type that accepts the variable. Examples of simple uses are as follows:

# Example: String formatting

Name = ' 17jo '
print ' www.%s.com '%name
>> www.17jo.com

Name = ' 17jo '
Zone = ' com '
print ' www.%s.%s '% (name,zone)
>> www.17jo.com

The string is formatted with a different format symbol, representing the different types to be converted, as shown below.

Format Symbol Presentation type

%s string
%d/%i decimal Integer
%u decimal integers
%o octal integers
%x/%x hexadecimal integer
%e/%e Science Count
%f/%f floating-point numbers
%% OUTPUT%

When the format symbol is a number, it can be preceded by an amount and a fill position such as:%[0][total digits [.] [Decimal places] to set the style to be converted, using the following methods:

# Example: Number formatting

nyear = 2018
Nmonth = 8
Nday = 18
# format Date%02d number into two-bit integer vacancy 0
print '%04d-%02d-%02d '% (nyear,nmonth,nday)
>> 2018-08-18 # Output results

Fvalue = 8.123
print '%06.2f '%fvalue # preserves 2-bit decimal floating-point type with width 6
>> 008.12 # Output

print '%d '%10 # output decimal
>> 10
print '%o '%10 # output octal
>> 12
print '%02x '%10 # output two-bit hexadecimal, letter lowercase blank fill 0
>> 0a
print '%04x '%10 # output four-bit hex, letter-Uppercase vacancy supplement 0
>> 000A
print '%.2e '%1.2888 # with scientific notation output floating-point type keep 2 decimal digits
>> 1.29e+00

The above article on the Python string format output (format/printf) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.