Left and right alignment issues with print function output in Python

Source: Internet
Author: User

In order to align the output of the print function, the author finds the right and left alignment method in http://www.jb51.net/article/55768.htm. Tidy up as follows:

One, numeric type (int, float)

#%d,%f is a placeholder
>>> A = 3.1415926
>>> print ("%d"%a) #%d can only output integers, int class
3
>>> print ("%f"%a) #%f output floating-point number
3.141593
>>> print ("%.2f"%a) #按照要求输出小数位数
3.14
>>> print ("%.9f"%a) #如果要求的小数位数过多, followed by 0 complement
3.141592600


>>> B = 3
>>> print ("%4d"%b) #如果是整数, which requires the integer to occupy four positions, thus adding three spaces to the front
3 #而不是写成0003的样式

>>> print ("%06d"%int (a)) #整数部分的显示, requires a total of 6 bits. If the integer is less than 6 bits, then the insufficient number of digits is preceded by 0 in the integer.
000003

>>> print ('%06d '%b)
000012

In practical programming, we often need to write a=xxx style to make the output interface more friendly. So the author also copied the source of the original link author of a section of code, slightly modified to give the Python3 expression paradigm.

(1) Right align

>>> print ("pi=%10.3f"%a) #约束一下, meaning that the integer part plus the decimal and fractional parts amounts to 10 bits, and right-aligned
Pi= 3.142

(2) Align Left
>>> print ("pi=%-10.3f"%a) #要求显示的左对齐, the rest is the same as above
pi=3.142

Second, character type (str)

is similar to a numeric type, but changes the placeholder for%d,%f to the placeholder for%s.

Left and right alignment issues with print function output in Python

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.