On Python string format output (format/printf)

Source: Internet
Author: User
Tags python string format
The Python string is formatted using the "character% format 1% format 2 characters"% (variable 1, variable 2), and the% format represents the type of the accepted variable. Simple examples of use 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 after the percent sign, representing the different types to be converted, and the specific representation symbol is shown below.

Format symbol representation type

%s string
%d/%i decimal Integer
%u decimal integer
%o Eight-binary integers
%x/%x hexadecimal integer
%e/%e Scientific counting
%f/%f floating Point
% OUTPUT%

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

# example: Numeric formatting

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

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

print '%d '%10 # output decimal
>> 10
print '%o '%10 # output octal
>> 12
print '%02x '%10 # output two-bit hex, letter lowercase blank complement 0
>> 0a
print '%04x '%10 # output four-bit hex, letter capital Vacancy 0
>> 000A
print '%.2e '%1.2888 # Output floating-point type with scientific notation reserved 2 decimal places
>> 1.29e+00

This article on the Python string format output (format/printf) is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support the script home.

  • 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.