Python string formatting

Source: Internet
Author: User
Tags vars

Modifier between% and the conversion character

    • -, left alignment flag, default to right alignment
    • +, display numeric symbol
    • 0, 0 padding
    • A number that specifies the minimum width
    • . A decimal point, followed by the number of digits (the maximum number of strings, the number of digits after the float, the smallest number of integers )
    • * For replacing field widths
1 Print('%*.*f'% (10, 2, 3.14159))2 Print('%.4s,%.5d,%.3f'% ('Hello', 16, 3.14159))3 Print('% (key) 010d,% (name) 10s'% {'Key': 123,'name':'Ron'})4 5 #VARs () function Tips6Name ='Ron'7Age = 258 Print('% (name) s is% (age) +d years old'% VARs ())

Advanced string Formatting S.format

    • {n} n is an integer: replaced by positional parameter
    • {name}: Replaced by keyword parameter
    • {{}}: output {}
    • {Name[n]}: Sequence Lookup
    • {Name[key]}: Dictionary Lookup
    • {name.attr}: Property Lookup
    • {PLACE:FORMAT_SPEC}: Specify format
      • [Fill[align][sign][0][width][.precision][type]]
      • <,^,>: Align Left and right

1 Print("{0},{1},{0}". Format ('Hello',' World'))2 Print("{Name}, {age}". Format (age=25, name='Ron'))3 Print('{0}, {age}'. Format ('Hello', age=22))4 Print('{{Hello}}, {}'. Format (123))5 Print('{name[1]}'. Format (name=[1,2,3]))6 Print('{Name[key]}'. Format (name={'Key':'Hello'}))7 Print('{0.__doc__}'. Format (str))8 Print("{0.real} {0.imag}". Format (3 + 4j))9 Print("{name:>8},{age:*^8d}, {high:8.2f}". Format (name='Ron', Age=25, high=176.567))Ten  Onex = 42; y = 3.14159 A Print('{0:010b}'. Format (x)) - Print('{0:010x}'. Format (x)) - Print('{0:+010.2f}'. Format (y)) the Print('{0:<+10.2%}'. Format (y)) - Print('{0:{width}.{ PRE}F}'. Format (y, width=10, pre=3)) - Print('{0!r:^20}'. Format ('Guido'))

Python string formatting

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.