Python string formatting uses "character % format 1 % format 2 character" % (variable 1, variable 2), % format indicates the type of variable accepted. A simple usage example is as follows:
# Example: String formatting
Name = '17jo'
print 'www.%s.com'%Name
>> www.17jo.com
Name = '17jo'
Zone = 'com'
print 'www.%s.%s'%(Name,Zone)
>> www.17jo.com
When formatting strings, there are different format symbols after the percent sign, which represent different types to be converted. The specific symbols are as follows.
Format symbol indicates type
%s String
%d/%i Decimal integer
%u decimal integer
%o Octal integer
%x/%X Hexadecimal integer
%e/%E Scientific notation
%f/%F Floating point number
%% Output%
When the format symbol is a number, you can add a number and fill in the missing digits in front, such as: %[0][Total digits][.][Decimal digits] to set the style to be converted. The specific usage is as follows:
# Example: Number formatting
nYear = 2018
nMonth = 8
nDay = 18
# Format the date %02d number into a two-digit integer and fill in the gaps with 0
print '%04d-%02d-%02d'%(nYear,nMonth,nDay)
>> 2018-08-18 # Output results
fValue = 8.123
print '%06.2f'%fValue # Reserve a 2-digit decimal floating point type with a width of 6
>> 008.12 # Output
print '%d'%10 # Output decimal
>> 10
print '%o'%10 # Output octal
>> 12
print '%02x'%10 # Output two digits of hexadecimal, fill in the gaps with zeros in lowercase letters
>> 0a
print '%04X'%10 # Output four digits of hexadecimal, fill in the gaps between uppercase letters with zeros
>> 000A
print '%.2e'%1.2888 # Output floating point type in scientific notation retaining 2 decimal places
>> 1.29e+00
The above article briefly talks about Python string formatted output (format/printf) is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.