Python str Operation Method
1. str. format (): format the string using the "{}" Placeholder (the index number format and key-value pairs in the placeholder can be used together ).
>>> String = 'python {}, django {}, tornado {}'. format (2.7, 'web', 'tornado ') # The number of {} placeholders corresponds to the number of values, which are entered in the string in order.
>>> String
'Python2.7, djangoweb, tornadotornado'
>>> String = 'python {}, django {}, tornado {} '. format (2.7, 'web ')
Traceback (most recent call last ):
File "", line 1, in
String = 'python {}, django {}, tornado {} '. format (2.7, 'web ')
IndexError: tuple index out of range
>>> String = 'python {0}, django {2}, tornado {1 }'. format (2.7, 'web', 'tornado ') # You can also specify the value to be entered (starting from 0, the subsequent values may not always be used, however, make sure that the specified position has a value)
>>> String
'Python2.7, djangotornado, tornadoweb'
>>> String = 'python {py}, django {dja}, tornado {tor }'. format (tor = 'tornado ', dja = 'web', py = 2.7) # values can be assigned using key-value pairs.
>>> String
'Python2.7, djangoweb, tornadotornado'
>>>
Python str Operation Method
2. Use "%" to format the string.
Format a symbol table
% C to single character
% R is converted to a string expressed by repr ().
% S is converted to a string expressed by str ().
Convert % d or % I to a signed decimal integer
% U to an unsigned decimal integer
% O to an unsigned octal integer
% X is converted into an unsigned hexadecimal integer. The hexadecimal letter is in lowercase.
% X is converted into an unsigned hexadecimal integer, and hexadecimal letters are written in uppercase.
% E is converted to a floating point number expressed in scientific notation, where e is expressed in lowercase.
% E is converted into a floating point number expressed in scientific notation, where E is expressed in uppercase.
% F or # F convert to floating point number
% G is automatically converted to % e or % f by Python based on the number size.
% G is automatically converted to % E or % F by Python based on the number size.
% Output "%"
Auxiliary formatting symbol table
* Defines the width or decimal point precision.
-Left alignment
+ Positive number output positive value symbol "+"
When the number size is less than m. n, fill in space
# Display 0 before the octal digit, and 0x or 0X before the hexadecimal digit
When the size of 0 numbers is less than m. n, use 0 to fill
M. nm is the minimum total display width, and n is the number of digits after the decimal point (if available)