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

6. python string formats the expression


May 10, 2021 Python2


Table of contents


6. Python string formats the expression

String formatting allows multiple specific types of substitutions to be performed on a string in a single step

Especially when giving tips to users, formatting is very convenient

How to implement it:

1. Format the expression, similar to the printf in the c language

In an expression, we use the % binary operator

  >>> print('this is %d %s bird' % (1,'dead'))  
  this is 1 dead bird  

Take the example above (note that the % we're talking about below is based on the one in the middle of the string and the metagroup)

Place a string on the left side of % that contains one or more embedded objects that start with %

Put one (or more) objects on the right side of % that are embedded in the metagroup, which are inserted into the conversion target position on the left

  >>> name='ray'  
  >>> 'my name is %s' % name  
  'my name is ray'  
  >>> '%d %s %d you' % (1,'spam',4)  
  '1 spam 4 you'  
  >>> '%s---%s---%s' % (42,3.14,[1,2,3])  
  '42---3.14---[1, 2, 3]'  
  >>>   

When you insert multiple objects, you need to put them in a single group

2. Advanced formatting expressions

The string formats the list of code

Code Significance
s String (or any object)
R s, but with repr, not str
C Character
D A hedding integer
Integer
u No integer
O Octal integers
Hetey integers
x, but print capital
E Floating-point index
E e, but print capital
F Floating-point hete ten-party system
F Floating-point hete ten-party system
G Floating point e or f
G Floating point e or f
% Constant %

%[(name)][flags][width][.pression]typecode

Example


  >>> x=1234  
  >>> res='integers:...%d...%-6d...%06d' % (x,x,x)  
  >>> res  
  'integers:...1234...1234  ...001234'  
  >>>   

%e, %f, %g are different for floating-point printing

  >>> x=1.23456789  
  >>> x  
  1.23456789  
  >>> '%e|%f|%g' % (x,x,x)  
  '1.234568e+00|1.234568|1.23457'  
  >>>   

3. Dictionary-based formatted expressions

  >>> 'my name is %(name)s,my age is %(age)d' % {'name':'ray','age':30}  
  'my name is ray,my age is 30'  
  >>>   

To put it actually, name each replacement location so that the code looks clearer