format string
- Python uses a string as a template
- The template contains a format character, reserving a location for the real value
- Use a tuple or dictionary to pass a value
- Between the template and the value, use% to represent the formatting operation
Example:
1) Tuple transfer value
Print ("I ' m%s, and I ' m%d years old" % (' Tony ', 99))
2) Dictionary transfer value
Print ("I ' m% (name) s, and I ' m% (age) D years old" % {' name ': ' Tony ', ' Age ': 99})
When the dictionary is passed the value, we name the format string. So you can receive the value of the dictionary (key of the same name)
Format character meaning:
%s string (displayed with str ())%r string (display with repr ()%c single character%b binary integer%d decimal integer%i decimal integer%o octal integer% x hexadecimal integer%E exponent (base write e)%E exponent (base write e)%f floating-point number%f floating-point number with the same%G exponent (e) or floating-point number (based on display length)%G exponent ( E) or floating-point number (depending on the display length) the percent character "%"
Attention:
1) The difference between%s and%r is that%s does not have a ' ',%r with
Print ("%s"% ' abc ') # Abcprint ("%r"% ' abc ') # ' abc '
2) Percent does not understand??
3) In fact, in addition to naming , there are other options to control the string.
% [(name)] [flags] [width]. [Precision] TypeCode
- Where flags have +,--, 0, ' four kinds. Indicates that the string is pre-fill with these symbols
- Width indicates the output length of the string, the left complement
- Precision represents the output precision of the float type
Example:
Print ("%+10x"%) # +aprint ("%04d"% 5) #0005print ("%6.3f"% 2.3) # 2.300# width and precision You can also dynamically pass print ("%.4f"% 1.2) #1.2000print ("%.*f"% (4,1.2)) #1.2000
Python% formatted string