String formatting alignment __python in Chinese in Python python

Source: Internet
Author: User

Chinese characters occupy the equivalent of two words in the character, but the font design, the general one Chinese character width does not equal to the width of two English characters, so the effect of printing is biased.

Such as:

c = [' Summary ', ' summary ', ' summary ', ' summary ', ' summary ', ' summary ', ' summary ', ' decision ', ' the ' determined '
]
print ('---- Normal string format:----') for
x in range (len (c)):
    print (' |%20s| '% c[x])
Print the results as shown in the following illustration:



However, the width of the equal-width character is exactly equal to the width of two English characters in a Chinese font. We can calculate the length of the string automatically according to this.

def Chinese (data):
    count = 0 for
    s in data:
        if Ord (s) > 127:
            count + 1 return
    count

prin T ('----format by function calculation length:----') for
x in range (len (c)): Number
    = Chinese (c[x])
    newstr = ' {0:{wd}} '. Format (c[ X],wd=20-number)
    print (' |%s| '% newstr)


github:https://github.com/jueee/04-liaoxuefeng/blob/master/81-chinese.py


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.