Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

7. python string formatting method (1)


May 10, 2021 Python2


Table of contents


7. Python string formatting method (1)

In the previous section, another way to say string formatting in this section is to call format()

  >>> template='{0},{1} and {2}'  
  >>> template.format ('a','b','c')  
  'a,b and c'  
  >>> template='{name1},{name2} and {name3}'  
  >>> template.format (name1='a',name2='b',name3='c')  
  'a,b and c'  
 >>> template='{name1},{0} and {name2}'  
  >>> template.format ('a',name1='b',name2='c')  
  'b,a and c'  
  >>>   

Here's an example from above

1. The replacement location can be marked with the subsetitution

2. The replacement location can be replaced by a name

Let's talk about adding properties to the method

  >>>import sys  
  >>> 'my {1[spam]} runs {0.platform}'.format(sys,{'spam':  
                           'laptop'})  
  'my laptop runs win32'  
  >>>   
  >>> 'my {config[spam]} runs {sys.platform}'.format(sys=sys,config={'spam':'laptop'})  
  'my laptop runs win32'  
  >>>   

In the two examples above, the first reads the string and the second reads the platform property inside sys

Here's another example of using offsets in an expression

  >>> aList=list('abcde')  
  >>> aList  
  ['a''b''c''d''e']  
  >>> 'first={0[0]} third={0[2]}'.format (aList)  
  'first=a third=c'  
  >>>   

Note: When using offsets, you can only be positive integers, you can't use negative numbers, you can't use positive integers that represent intervals

  >>> aList=list('abcde')  
    
  >>> aList  
  ['a''b''c''d''e']  
  >>> 'first={0[0]} third={0[-1]}'.format (aList)  
  Traceback (most recent call last):  
    File "", line 1in   
      'first={0[0]} third={0[-1]}'.format (aList)  
  TypeError: list indices must be integers, not str  
  >>> 'first={0[0]} third={0[1:3]}'.format (aList)  
  Traceback (most recent call last):  
    File "", line 1in   
      'first={0[0]} third={0[1:3]}'.format (aList)  
  TypeError: list indices must be integers, not str  
  >>>