Home  >  Article  >  Backend Development  >  An in-depth explanation of Python string formatting

An in-depth explanation of Python string formatting

高洛峰
高洛峰Original
2016-10-17 11:50:481475browse

The string formatting operator (%) is very similar to the string formatting of the printf() function in the C language. Even the symbols used are the same, using the percent sign (%), and supports all printf() formatting operations. The syntax is as follows:

format_string % string_to_convert

format_string is the format mark string, in the form of "%cdoe"; string_to_convert is the string to be formatted. If there are more than two, they need to be enclosed in parentheses.

An in-depth explanation of Python string formatting

String formatted output example:

charA = 65
charB = 66
print("ASCII码65代表:%c" % charA)
print("ASCII码66代表:%c" % charB)
Num1 = 0xEF3
Num2 = 0xAB03
print('转换成十进制分别为:%u和%u' % (Num1, Num2))
Num3 = 1500000
print('转换成科学计数法为:%e' % Num3)

Output:

ASCII code 65 represents: A

ASCII code 66 represents: B

converted to decimal: 3827 and 43779

converted to scientific notation The method is: 1.200000e+06


Formatting characters can also be used together with auxiliary symbols, which is very convenient.

Auxiliary symbols, as shown in the following table:

An in-depth explanation of Python string formatting

Example of auxiliary symbols:

Num1 = 108
print("%#X" % Num1)
Num2 = 234.567890
print("%.2f" % Num2)

Output:

0X6C

234.57


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn