Python string formatting

Source: Internet
Author: User

There are two ways to format strings in Python3:% and format

One,%

Place a string on the left side of the% operator that needs to be formatted, with one or more embedded translation targets, beginning with%, such as%s,%d,%f.

Place an object to the right of the% operator, which will be inserted on the left side where you want Python to format the string as a translation destination.

Case:

>>> ' This is a%s '% ' test ' "This is a test ' >>>>>> ' Shuangji%d.this is a%s '% (666, ' Test ') #右侧有多个值时用括号括起来 ' Shuangji 666.this is a test ' >>>>>> '%s--%s--%s '% (666,231.51241,[1,2,3]) # Any type in Python can be converted to a string. The left side of the instance is%s, and the object in the right is converted to a string (re-created). ' 666--231.51241--[1, 2, 3] ' >>>

% left common structure is%[(name)][flags][width width][.precision precision]typecode,-left alignment, + sign, 0 complement 0

>>> x=1234>>> test= '%d...%-6d...%06d '% (x,x,x)        The   #-is left-aligned. 0 Insufficient digits 0 >>> test ' 1234 ... 1234 &NBSP, ..... 001234 ' >>> x=12.126435787654123                      #浮点数的表示方法 >>>  '%e|%f|%g '% (x,x,x) ' 1.212644e+01|12.126436|12.1264 ' >>>  '%-6.2f|%0 6.2f|%+06.1f '% (x,x,x)              #6.2 indicates a total of 6 digits, 2 decimal places ' 12.13 |012.13|+012.1 ' >>>  '%-6.2f|%0 6.2f|%.*f '% (x,x,4,x)              #此处 * Indicates accuracy, 4 to * after X is the alternative value ' 12.13 |012.13|12.1264 ' >>>>>>  '% (a) s % (b) s % (c) s % (d) s '  %   ({' A ': ' This ', ' B ': ' Is ', ' C ': ' A ', ' d ': ' Test '})          #基于字典的格式化, is to use a key value. ' This is a test '

Second, Format method

>>>  ' this {} a {} '. Format (' is ', ' test ')               #默认1对1, 1 more, 1 not ' this is a test ' >>>  ' this {1}  a {0} '. Format (' is ', ' test ')             # {} Locate the replacement target and insert the parameter ' this test a is ' >>>  ' this {x} a {y} ' by location. Format (x= ' Is ', y= ' test ')             #{} to find the replacement target and insert parameters by keyword ' this  is a test ' >>>  ' this {x} a {0} '. Format (' is ', x= ' test ')               #两者都有 ' This test a is ' >>> >>>  ' This {1[spam]} test of {0.platform} '. Format (sys,{' spam ': ' Is '})       #0表示第一个位置,.platform  represents the object properties referenced by the location or keyword: sys.platform. ' This is test of linux ' >>>

The

Format format structure {Fieldname!conversionflag:formatspec},fieldname represents a numeric position or keyword for the parameter, Conversionflag can be r,s,a corresponding repr/str/ One invocation of the ASCII built-in function, Formatspec specifies how the value is represented: field width, alignment, fill 0, decimal precision, and so on. The Formatspec form after the colon is: [[fill]align alignment][sign][#][0][width width][.precision precision][typecode]

>>> ' {0:>10}={1:<10} '. Format (' Test ', 12.62424) #字段宽度为10个,> right-aligned,< left-aligned ' test=12.62424 ' >&G T;> import sys>>> ' {0.platform:>10}={1[item]:<10} '. Format (sys,dict (item= ' laptop ')) # Use the location. Property method to replace the value ' linux=laptop ' >>>>>> ' {0:.2f} '. Format (1/3.0) ' 0.33 ' >>> ' {0:.{ 1}F} '. Format (1/3.0,4) #动态的从参数列表获取精度位数 ' 0.3333 ' >>> ' {%.*f} '% (6,1/3.0) #动态的使用% get precision digits from the argument list ' {0.333333} ' & Gt;>>

Advanced usage

        >>> msg= ' This {a} a {b} for &NBSP;PYTHON,THE&NBSP;NO.{C} '. Format (**{' A ': ' Is ', ' B ': ' A ', ' C ': 1})               #使用字典形式来格式化, you must add two  * numbers and braces          >>> print (msg)         this is a a  for python,the no.1        >>>         >>> msg= ' this {:s} a {:s} for python,the  no.{:d} '. Format (' is ', ' test ', 1)                          >>> print (msg)          this is a test for python,the no.1      &nbSp;  >>>        >>> msg= ' this {: s} a {:s} for python,the no.{:d} '. Format (*[' is ', ' test ', 1])               #列表形式加入一个 *, * indicates that the elements in the list are traversed, similar to the one in the preceding column          >>> print (msg)         this  Is a test for python,the no.1        >> >


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.