The string formatting operator (%), which is very similar to the string formatting of the printf () function in C language. It even uses the same symbols and uses the percent sign (% ), it also supports all printf (string formatting operator (%), which is very similar to the string formatting of the printf () function in C language, and even uses the same symbol, with a percent sign (% ), all printf () formatting operations are supported. Syntax:
Format_string % string_to_convert
Format_string is a string in the format of "% cdoe"; string_to_convert is the string to be formatted. if there are more than two strings, they must be enclosed in parentheses.
String formatting symbol
Format symbols |
Description |
% C |
Convert to a character (ASCII value, or a string of the same length) |
% S |
Converts a string to a string with the str () function prior to string conversion. |
% D |
Convert to a signed decimal number |
% U |
Convert to unsigned decimal number |
% O |
Convert to the unsigned octal number |
% X |
(Unsigned) to an Unsigned hexadecimal number |
% E |
Convert to scientific notation |
% |
Output % |
% X |
(Unsigned) is converted to an Unsigned hexadecimal number. after conversion, hexadecimal characters are capitalized, which is similar to % e (lowercase after conversion) |
Example of string formatting output:
CharA = 65 charB = 66 print ("ASCII code 65 stands for: % c" % charA) print ("ASCII code 66 stands for: % c" % charB) num1 = 0xEF3Num2 = 0xAB03print ('convert to decimal: % u and % u' % (Num1, Num2) Num3 = 1500000 print ('convert to scientific notation: % E' % Num3)
Output:
ASCII code 65:
ASCII code 66: B
Convert to decimal: 3827 and 43779, respectively.
Convert to scientific notation: 1.200000e + 06
Formatting characters can also be used with auxiliary symbols, which is very convenient.
Auxiliary symbols, as shown in the following table:
Auxiliary symbol |
Description
|
* |
Define the width or decimal point precision |
- |
Align left |
+ |
Displays the plus sign (+) before a positive number) |
|
A space is displayed before a positive number. |
# |
Zero (0) is displayed before the octal number, and "0x" or "0X" is displayed before the hexadecimal number (depending on whether "x" or "X" is used ") |
0 |
Fill "0" in front of the displayed number instead of the default space |
M. n |
Is the minimum total width displayed, and n is the number of digits after the decimal point |
Note: The secondary symbol must be between the percent sign (%) and the formatted symbol.
Auxiliary symbol example:
Num1 = 108print("%#X" % Num1)Num2 = 234.567890print("%.2f" % Num2)
Output:
0X6C
234.57
The above is a detailed introduction to Python string formatting. For more information, see other related articles in the first PHP community!