Python string formatting output (format/printf) and pythonprintf

Source: Internet
Author: User

Python string formatting output (format/printf) and pythonprintf

For Python string formatting, use "character % format 1% Format 2 characters" % (variable 1, variable 2), and % format to accept the type of the variable. A simple example is 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

When a string is formatted, the hundred semicolons are followed by different format symbols, representing different types of conversion. The specific symbols are shown below.

Format Symbol Representation type

% S string
% D/% I decimal integer
% U decimal integer
% O octal integer
% X/% X hexadecimal integer
% E/% E scientific count
% F/% F floating point number
% Output %

When the format symbol is a number, you can add a number and a fill space, for example, % [0] [total digits] [.] [number of decimal places] to set the style to be converted. The usage is as follows:

# Example: Digital formatting

NYear = 2018
NMonth = 8
NDay = 18
# Convert the format date % 02d to two integer types. Enter 0.
Print '% 04d-% 02d-% 02d' % (nYear, nMonth, nDay)
> # Output results

FValue = 8.123
Print '% 06.2f' % fValue # retain the 2-digit floating point type with a width of 6
> 008.12 # output

Print '% d' % 10 # output decimal
> 10
Print '% o' % 10 # output gossip
> 12
Print '% 02x' % 10 # output two hexadecimal letters, lowercase letters fill blank
> 0a
Print '% 04x' % 10 # output 4-digit hexadecimal format, uppercase letters fill blank
> 000A
Print '%. 2e' % 1.2888 # use scientific notation to output floating point type to retain 2 decimal places
> 1.29e + 00

The above discussion about the format/printf of the Python string is all the content shared by the editor. I hope you can give us a reference and support the help house.

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.