Using the print() function
In Python, the print() function supports formatted output, similar to C's printf.
1. Formatting output strings and integers
[Example 1] Output the string AmoXiang, and calculate and output its character length.
str1 = "% = %d" % ("AmoXiang", len("AmoXiang")) print(str1) # exports = 8
The % represents the formatting operator in a string, which must be followed by an additional formatting symbol, as described in the following table.
The %() tuple can contain one or more values, such as variables or expressions, which are used to pass values to the % operator in the string. The number and order of the elements in the tuple must correspond to the % operator in the string, otherwise an exception will be thrown. The %() tuple must be located after the string, otherwise it is invalid. If the string contains only one % operator, then you can also pass the value directly. Example:
str1 = " = %d" % len("AmoXiang") print(str1) # exports = 8
2. Formatting the output in different binary systems
[Example 2] Use the print() function to output numbers as strings in hexadecimal, decimal, or octal format.
num = 123 # Output: Hex = 7b Dec = 123 Oct=173 print("Hex = %x Dec = %d Oct=%o" % (num, num, num))
Addendum: Integer types include decimal integers, octal integers, hexadecimal integers, and binary integers.
Decimal integers cannot begin with 0. Octal integers consist of 0 to 7, octal to one, and begin with 0o or 0O, e.g.: 0o23 Hexadecimal integers consist of 0 to 9 and a to f, hexadecimal to one, and begin with 0x or 0X. Example: 0x23 Binary integer consisting of 0 and 1, rounded to one, starting with 0b or 0B. For example: 0b101 If you don't understand this point, you can click Conversion to learn about it.
3. Formatting output floating-point numbers
[Example 3] Output a number as a floating-point string in a different format.
PI = 3.141592653 print("pi1 = %10.3f" % PI) # Total width of 10, decimal precision of 3 print("pi2 = %.*f" % (3, PI)) # * denotes reading 3 from the tuple that follows, defining precision print("pi3 = %010.3f" % PI) # Fill in the blanks with zeros print("pi4 = %-10.3f" % PI) # Left-justified, total width 10 characters, decimal precision 3 print("pi5 = %+f" % PI) # Display a plus sign in front of a floating point number
The program runs with the following results:
When formatting output numbers or strings, auxiliary instructions can be attached to refine the formatting operation. The specific instructions are shown in the following table:
II. Using the () method
%
Operators are the basic method of formatting output traditionally, but starting with Python version 2.6, a new formatting method has been added for string data()
It passes{}
operator and:
An auxiliary instruction to replace the%
Operator.
[Example 1] By position index value
print('{0} {1}'.format('Python', 3.7)) # Python 3.7 print('{} {}'.format('Python', 3.7)) # Python 3.7 print('{1} {0} {1}'.format('Python', 3.7)) # 3.7 Python 3.7
In strings you can use the{}
as a formatting operator. As opposed to the%
operator differs in that the{}
The operator can customize the position of the referenced value by the included positional value, and can also duplicate references.
[Example 2] Indexing values by keywords
# Output: Amo's age is 18. print('{name}Age is{age}year (of crop harvests)。'.format(age=18, name="Amo"))
[Example 3] Indexing by subscripts
L = ["Jason", 30] # Output: Jason's age is 30. print('{0[0]}Age is{0[1]}year (of crop harvests)。'.format(L))
By using the format() function, which is a convenientmap (math.)
way, lists and tuples can bebeat (an egg)
The format() method contains a rich set of formatting qualifiers, which are included in the{}
operator:
behind the symbol.
1. Filling and alignment
:
The symbol can be followed by a padded character, which defaults to a space.^、<、>
Indicates centered, left-aligned, and right-aligned, respectively, followed by a width qualifier.
[Example 4] The following example is designed to output 8-bit characters with different fill characters and value alignment.
print('{:>8}'.format('1')) # 8 total width, right-justified, default space padding print('{:0>8}'.format('1')) # Total width of 8, right-aligned, using 0 padding print('{:a<8}'.format('1')) # The total width is8,left justification,utilizationapadding
The program runs with the following results:
2. Accuracy and typef
Example 5: Using f with float type data
print('{:.2f}'.format(3.141592653)) # output result:3.14
included among these.2f
indicates that the precision after the decimal point is 2, and f indicates floating-point output.
3. Progressive digital outputs
[Example 6] Use b, d, o, and x to output binary, decimal, octal, and hexadecimal numbers, respectively.
num = 100 print('{:b}'.format(num)) # 1100100 print('{:d}'.format(num)) # 100 print('{:o}'.format(num)) # 144 print('{:x}'.format(num)) # 64
4. Thousand-separated outputs
[Example 7] Use the comma (,) to output the thousand separator of the amount.
print('{:,}'.format(1234567890)) # 1,234,567,890
The format() function in detail
format () function can format the data processing operations. The syntax format is as follows:
format_spec is the formatting interpretation. When the parameter format_spec is null, equivalent to the way the function str(value). value is the data to be converted. format_ spec can be set to a very complex format conversion parameters, to generate a more complete data formatting template. format_spec is written in the following form:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
format_spec The formatting controllers can be categorized into major applications such as text alignment, padding values, flag setting, formatting, type conversion, and kilobytes (grouping of numbers). The refined classification is illustrated in the following figure:
Parameter Description:
(1) fill (fill value): here you can fill in any character, usually used together with align, width, to achieve the specified number of characters to fill the digits, the usual format as shown in Figure 1.2, fill the effect and position as shown in Figure 1.3.
Usually with0、*、#、@
etc. for padding. If you do not write a fill value, the default fill value is used, which is a space. The code is as follows:
# 81@@@@@@@@ print(format(81, '@<10')) # Filled with @ symbols, 10 spaces wide # @@@@@@@@81 print(format(81, '@>10')) # expense or outlay@Symbol Filling,The width is10space
(2) align (alignment): refers to the alignment of the output in width (digital width), respectively, using the<、>、^、=
The 4 symbols indicate left-aligned, right-aligned, center-aligned, and number-filled (for numbers only, with a fill after the symbol).
(3) width (digital width): refers to set the width of the output character, if the actual number of bits of the data is larger than the width specified width value, the actual length of the data is used. If the actual number of bits of the value is less than the specified width, the number of bits will be set to fill the fill value or set to fill the value of 0, if not set to fill the value, then fill with spaces.
s = "PYTHON" print(format(s, '10')) # No identifiers, if it is a string then it is left-justified by default, and the part that is not wide enough is filled with spaces by default print(format(13.14, '10')) # No identifiers, defaults to right-justified if it is a number, defaults to a space if it is not wide enough print(format(s, '0>10')) # Right-aligned, with 0's for widths less than specified print(format(s, '>04')) # Right-aligned, because the actual width of the character is greater than the specified width 4, without padding print(format(s, '*>10')) # Right-aligned, with "*" filling in the gaps. print(format(s, '>010')) # Right-aligned, underfill with zeros print(format(s, '>10')) # Right-aligned, space-filled by default print(format(s, '<10')) # Left-aligned, space-filled by default print(format(s, '<010')) # Left-aligned, underfill with zeros print(format(s, '@^10')) # center-aligned, underfill with '@', 10 spaces wide print(format(13.14, '0<10')) # Left-aligned, underfill with zeros print(format(13.14, '@^10')) # center-aligned, underfill with @ print(format(13.14, '0>10')) # Right-aligned, underfill with zeros print(format(-13.14, '0=10')) # right-aligned,Symbols followed by an insufficient portion of the symbol are denoted by0padding
The program runs with the following results:
(4) precision (accuracy): the precision is determined by the decimal point..
Beginning. For floating point numbers, precision indicates the number of significant digits in the decimal part of the output. For strings, precision indicates the maximum length of the output. precision is usually used in conjunction with type.
(5) type (type): indicates the output string, integer and floating-point number type format rules, the default is character type s. For integer type, the output format includes 7 kinds:
b: outputs the binary mode of the integer. c: outputs the Unicode character of the integer. d: outputs the decimal mode of the integer. n: outputs the decimal mode of the integer. o: outputs the octal mode of the integer. x: outputs the lowercase hexadecimal mode of the integer. Similar to d when the value is an integer, and similar to g when the value is a floating point number. The difference is that n uses the current locale to insert the appropriate digit separator character. x: outputs the integer in uppercase hexadecimal.
For floating point types, there are seven output formats:
e: output the exponential form of the lowercase letter e corresponding to a floating-point number. e: output the exponential form of the uppercase letter E corresponding to a floating-point number. f: output the floating-point representation of a floating-point number, retaining 6 decimal places by default. f: output the floating-point representation of a floating-point number, retaining 6 decimal places by default, and converting infinity to uppercase INF. g: auto-tuning to convert integer and floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and formatting them to the specified position (e in case of scientific notation). g: auto adjust to convert integer, floating point number to floating point or scientific notation (more than 6 digits in scientific notation), and format it to the specified position (e if scientific notation). g: auto adjust to convert integer, floating point number to floating point or scientific notation (more than 6 digits in scientific notation), and format it to the specified position (e if scientific notation). %: Output the percent form of a floating-point number. Application 1: Format Conversion
Use the format() function to convert formats. If format() is not supplied with the parameter format_spec, it defaults to formatting other formats as characters, which has the same effect as calling str(value). For example:
import datetime # Use the format() function to convert a floating-point number to a character, resulting in: '3.14' print(format(3.14)) # Use the str() function to convert a floating-point number to a character, resulting in: '3.14' print(str(3.14)) # Formatting the date as characters results in: '2021-01-17 05:25:02' print(format(().strftime("%Y-%m-%d %H:%M:%S")))
Set the value of the parameter format_spec, you can format the corresponding data types, strings can provide the parameter s. Decimal integers provide the parameter d and n, binary parameter b, octal parameter o, hexadecimal lowercase parameter x, hexadecimal uppercase parameter x, ASIIC code parameter c, floating-point number parameter f. The data types are all character types after the above formatting. The above formatted data types are all character types, as shown in the following example:
print(format(12.2, 'f')) # Convert to floating point, default to 6 decimal places, output: 12.200000 print(format(12, 'd')) # Converted to decimal, output: 12 print(format(13)) # Defaults to decimal without parameters, output: 13 print(format(13, 'n')) # Converted to decimal number, output: 13 print(format(13, 'b')) # Converted to binary, output: 1101 print(format(65, 'c')) # Convert Unicode to characters, output: A print(format(97, 'c')) # Convert Unicode to characters, output: a print(format(8750, 'c')) # Convert Unicode to characters, output: # print(format(12, 'o')) # Converted to octal, output: 14 print(format(12, 'x')) # Converted to hexadecimal lowercase representation, output: c print(format(12, 'X')) # Converted to hexadecimal capital letters,exports:C
Application 2: Generating Data Numbers
Numbering data with the format() function. Numbering data is also a way of formatting strings, using the format() function you can format strings for numbering. Simply set the padding characters (numbering is usually set to 0), and use the <, > and ^ symbols for left-, right-, and center-aligned when setting the alignment, and the symbols for the alignment padding in theheight
The output can be filled in the range. For 3-bit numbering of the number 1, right-justified, you need to set the fill character of the format() function to 0, the alignment to right-justified, and the width to 3. The specific code is as follows:
print(format(1, '0>3')) # Output: 001 print(format(1, '>03')) # Output: 001 print(format(15, '0>5')) # exports:00015
To generate the number is usually more complex, such as according to the date of the day to establish the number, or batch generation of the number, or will be given a batch of data in the number of digits converted to a fixed number of digits, the following code is given to achieve the number:
import datetime # Time + number wx = ().date() now = () print(str(wx), format(1, '0>3')) # Year-Month-Day + 3-digit number, output: 2021-01-17 001 print(format(now, '%Y-%m-%d'), format(1, '0>3')) # Year-Month-Day + 3-digit number, output: 2021-01-17 001 print(format(now, '%Y%m%d'), 'NO' + format(1, '0>3')) # Year-Month-Day + NO + 3-digit number, output: 20210117 NO001 print(format(now, '%d'), 'NO' + format(1, '0>3')) # Date + NO + 3 digit number, output: 17 NO001 print(format(now, '%H%M'), 'NO' + format(1, '0>3')) # hour-+ingredient +NO+3bit number,exports:1411 NO001
Batch generation of numbers:
# Batch generation of numbers for i in range(1, 6): print(format(i, '0>2'))
The program runs with the following results:
# Formatted list number # Format numbering of existing non-numbered digits nba = {1: 'Leonard', 2: 'Harden', 3: 'George'} for key, value in (): print(format(key, '0>3'), value)
The program runs with the following results:
To realize nested numbering, such as A001-A005, B001-B005, C001-005 nested numbering, the code is as follows:
for i in range(65, 69): for j in range(1, 6): data = chr(i) + format(j, '0>3') + ' ' print(data, end='') print()
The program runs with the following results:
Application 3: Formatting Decimal Integers
For different types of data, format() function's parameter format_spec provides different values, for decimal integers, integer values can be provided by the parameters d, n. Specifically as follows:
Application 4: Grid
print(format(81, '8d')) # 8-bit integer display with space padding in front of missing integers print(format(81, '+d')) # Formatted to display data as signed integers print(format(-81, '8d')) # Formatted to display as an 8-bit signed integer, with the complementary space placed before the sign print(format(81, '=8d')) # Formatted as an 8-bit positive integer, space-complemented print(format(-81, '=8d')) # Formatted as an 8-bit negative integer, with the shortfall padded after the negative sign print(format(81, '+8d')) # Formatted as an 8-bit positive integer with the shortfall padded before the sign print(format(-81, '8d')) # Formatted as an 8-bit negative integer, with the shortfall padded before the sign print(format(81, '>10')) # Right-aligned, 10 characters wide print(format(81, '<10')) # Left-aligned, 10 characters wide print(format(81, '010')) # Fill spaces with zeros, 10 characters wide print(format(81, '@<10')) # Fill spaces with "@", 10 characters wide print(format(81, '@>10')) # Fill spaces with "@", 10 characters wide print(format(+81, '=10')) # Right-aligned, 10 characters wide print(format(81, '0^10')) # Fill spaces with zeros, 10 characters wide s = 125 print(format(s, '0>10')) # Right-aligned, with 0's for widths less than specified print(format(s, '>04')) # Right-aligned, with 0's for widths less than specified print(format(s, '*>10')) # Right-aligned, with "*" padding for widths less than specified print(format(s, '>010')) # Right-aligned, specify 0 flag bit-filling print(format(s, '>10')) # Right-aligned, no padding value specified, space padding with default value print(format(s, '+^30')) # Align in the center and fill in the gaps with "+" print(format(s, '*<8')) # Right-aligned, with "*" padding for widths less than specified print(format(s, '08')) # right-aligned,indicate clearly and with certainty0Flag Bit Filling
formulaic floating point number
For floating point types, the parameters that can be supplied are e, E, f, F, g, G, n, %, None, and so on.
Representing a floating-point type with f can be preceded by a precision control, which is used to control the output width. If the number of output bits is greater than the width, the output is given in actual bits. You can also specify the sign for a floating-point number. + means that a positive sign + is displayed before a positive number. - A negative sign - (- is consistent with adding nothing ({:f})) before a negative number. A space indicates a space before a positive number and - before a negative number, and .3f indicates that the precision of the floating-point number is 3 (with 3 decimal places).
print(format(628, '.1f')) # Formatted as a floating point number with 1 decimal place, output: 628.0 print(format(628, '.2f')) # Formatted as a floating point number with 2 decimal places, output: 628.00 print(format(3.14159, '.1f')) # Formatted as a floating point number with 1 decimal place, output: 3.1 print(format(3.14159, '.2f')) # Formatted as a floating point number with 2 decimal places, output: 3.14 print(format(3.14159, '.5f')) # Formatted as a floating point number with 5 decimal places, output: 3.14159 print(format(-3.14159, '.3f')) # Formatted as a floating point number with 3 decimal places, output: -3.142 print(format(3.1415926535898, 'f')) # Default precision retains 6 decimals, output: 3.141593 # Default precision retains 6 decimals, with the shortfall filled with spaces, output: 3.141590 print(format(3.14159, 'f')) print(format(3.14159, '+.3f')) # Formatted as a signed floating-point number with 3 decimals print(format(3.14159, '>8.2f')) # Right-justified to 2 decimal places print(format(3.14159, '<10.2f')) # Left-justified, width 10, 2 decimal places, space in case of shortage print(format(3.14159, '<.3f')) # Left-justified with 3 decimal places print(format(3.14159, '@>10.3f')) # Right-aligned with "@" to fill in the gaps print(format(-3.14159, '=10.2f')) # Formatted as a 10-digit number with 2 decimal places, default padded with spaces print(format(-3.14159, '0=10.2f')) # Formatted as a 10-digit number with 2 decimal places and spaces filled with zeros print(format(3.14159, '0^10.2f')) # reservations2decimal10figure,center,spaces0padding
Application 5: Formatting Percentages
Displaying floating point numbers in percent can be accomplished by adding the % sign either alone or after the precision in the formatting explanation, for example:
print(format(0.161896, '%')) # Decimals formatted as percentages, output: 16.189600% print(format(0.161896, '.2%')) # Formatted as a percentage with 2 decimals, output: 16.19% print(format(0.0238912, '.6%')) # Formatted as a percentage with 6 decimal places, output: 2.389120% print(format(2 / 16, '.2%')) # Formatted as a percentage with 2 decimal places, output: 12.50% print(format(3.1415926, '.1%')) # Formatted as a percentage with 1 decimal place, output: 314.2% print(format(0.161896, '.0%')) # Formatted as an integer-preserved percent, output: 16% print(format(0.0238912, '8.6%')) # Formatted as an eighth percentile with 6 decimal places, output: 2.389120% print(format(0.0238912, '>8.3%')) # Formatted as a reservation3Percentages to eight decimal places,exports:2.389%
Application 6: Formatted scientific notation
To represent floating-point numbers in scientific notation, use e and E or g and G in the formatting templates. e is the universal power notation, which prints the number in scientific notation, and e represents the power. When g is used, the value is output in fixed-point format. When the value is particularly large, it is output as a power.
#####e and E print(format(3141592653589, 'e')) # Scientific notation, defaults to 6 decimal places, output: 3.141593e+12 print(format(3.14, 'e')) # Scientific notation, default 6 decimal places, output: 3.140000e+00 print(format(3.14, '0.4e')) # Scientific notation, default 4 decimal places, output: 3.1400e+00 print(format(3141592653589, '0.2e')) # Scientific notation with 2 decimal places, output: 3.14e+12 print(format(3141592653589, '0.2E')) # In scientific notation, with 2 decimal places, using upper case E. Output: 3.14E+12 #####g and G print(format(3.14e+1000000, 'F')) # Infinity to uppercase, output: INF print(format(3141592653589, 'g')) # Scientific notation with 2 decimal places, output: 3.14159e+12 print(format(314, 'g')) # Scientific notation with 2 decimal places, output: 314 print(format(3141592653589, '0.2g')) # In scientific notation, retaining 2 significant digits and using lowercase e, output: 3.1e+12 print(format(3141592653589, 'G')) # In scientific notation, with 5 decimal places, using upper case E. Output: 3.14159E+12 print(format(3.14e+1000000, 'g')) # decimal calculation,Convert infinity to lowercase,exports:inf
Application 7: Formatting Amounts
The format() function can also be used as a thousands separator for amounts. If you want to realize the amount of money in front of the form of symbols with the relevant currency, you need to manually add the appropriate currency symbols in front of the function. Such as:
print('$' + format(1201398.2315, '.2f')) # Add dollar sign and retain 2 decimal places print(chr(36) + format(1201398.2315, '.2f')) # ASCII add dollar sign, retain 2 decimal places print('¥' + format(78088888, ',')) # Add RMB symbols to differentiate amounts with thousands separators print('£' + format(7908.2315, '.2f')) # Add pound signs, differentiated by thousands separators print('€' + format(7908.2315, ',.2f')) # Add euro symbols, retain two decimal places, thousands separator print(chr(0x20ac) + format(1201398.2315, ',f')) # Adding the Euro Symbol Using Hexadecimal Encoding
The program runs with the following results:
Application 8: Formatting Characters
Formatting characters mainly includes intercepting strings, displaying strings in an aligned manner, filling strings, etc. The code is as follows:
print(format('PYTHON', 'M^20.3')) # Intercept 3 characters, width 20 centered, underfill with M print(format("PYTHON", '10')) # Default is left-centered, with spaces to fill in any gaps. print(format('', '.3')) # Intercept 3 characters, default left display print(format("PYTHON", '>10')) # Displayed on the right, with spaces to fill in any gaps. s = '' print(format(s, '0>20')) # Right-aligned, with 0's for widths less than specified print(format(s, '>4')) # Right-aligned, because the actual width of the character is greater than the specified width 4, without padding print(format(s, '*>20')) # Right-aligned, with the part of the width less than the specified width filled with *. print(format(s, '>020')) # Right-aligned, specify 0 flag bit-filling print(format(s, '>20')) # Right-aligned, no padding value specified, space padding with default value print(format(s, '+^30')) # center alignment,expense or outlay+Fill in the gaps
The program runs with the following results:
Application 9: Conversion
Conversion is mainly decimal, hexadecimal, octal, binary conversion, if it is hexadecimal, octal, binary number, it is best to retain the prefix of the conversion before the conversion of the system, such asOx/0o/0b
This ensures the accuracy of the conversion. The main binary conversion symbols are described below:
b: Binary. Outputs numbers in base 2. d: Decimal integer. Outputs numbers in base 10. o: Octal. Outputs numbers in base 8. x: Hexadecimal. Outputs numbers in base 16, with lowercase letters for numbers above 9.
The conversion codes for decimal, hexadecimal, octal, and binary are as follows:
print(format(77)) # format parameter is empty, default is decimal print(format(77, 'd')) # Originally a decimal number, converted to its original value print(format(-77, 'd')) # Originally a decimal number, converted to its original value print(format(77, '8d')) # Converted to 8 decimal digits, with spaces filled in the blanks print(format(-77, '8d')) # Converted to 8 decimal digits, negative numbers are padded with blank spaces before the minus sign print(format(77, '+8d')) # Converted to 8-bit signed decimal number with blank spaces before the sign print(format(-77, '08d')) # Converted to 8 decimal digits, negative numbers are padded with blank spaces before the minus sign print(format(77, '+08d')) # Converted to 8-bit signed decimal number with blank spaces before the sign print(format(-77, '#8d')) # Convert to 8-bit decimal number, add progressive flag print(format(-77, '=8d')) # Converted to 8 decimal digits with spaces filled in the blanks print(format(+77, '=8d')) # Converted to 8 decimal digits with spaces filled in the blanks print(format(+77, '*=8d')) # Converted to 8 decimal digits with blanks filled in * print(format(+77, '*=+8d')) # Converted to 8-bit signed decimal numbers with * padding between the sign and the data. print(format(-77, '#=8d')) # Convert to 8-bit decimal number, filling in the sign with the blank # print(format(+77, '*<8d')) # Converted to 8 decimal digits, left-justified, with blanks filled in* print(format(-77, '#>8d')) # Converted to 8 decimal digits, right-justified, with blanks padded # print(format(0X5A, 'd')) # Hexadecimal number 5A converted to decimal number, 0X for hexadecimal number print(format(0B011101, '+8d')) # Binary number 011101 converted to decimal number, 0B for binary number print(format(0O34, 'd')) # Octal number 34 converted to decimal number, 0O for octal number print(format(0O123456, '08d')) # Hexadecimal number 123456 converted to decimal number, underfilled with zeros print(format(+0X1234, '*>8d')) # hexadecimal number1234Convert to decimal number,right-aligned,not sufficient*
For numbers with decimal prefixes, such as 0x, 0o, 0b, they can be deleted by adding x, o, b directly after them.
print(format(0X5A, 'x')) # Remove the prefix of the hexadecimal number, output: 5a print(format(0B011101, 'b')) # Remove prefix from binary number, output: 11101 print(format(0O34, 'o')) # Removing prefixes from octal numbers,exports:34
Application 10: Formatting dates and times
The format() function can also format dates and times, and the formatting can be set using the date and time formatting symbols, which are commonly used in Python, as shown in Table 1.1.
The common operation codes are as follows:
import datetime now = () print(format(now, '%Y-%m-%d %H:%M:%S %A')) # Current time formatted as year-month-day + full English day of week print(format(now, '%Y-%m-%d %H:%M:%S %a')) # Current time formatted as year-month-day + abbreviated English day of the week # Chinese year-month-day display print(format(now, '%Y'), 'Year', format(now, '%m'), 'Moon', format(now, '%d'), 'Day') # Chinese time display print(format(now, '%H'), 'Year', format(now, '%M'), 'Points', format(now, '%S'), 'Seconds') print(format(now, '%Y-%m-%d %H:%M:%S %a')) # Current time formatted as year-month-day + abbreviated English day of the week print(format(now, '%Y-%m-%d')) # Current time formatted as standard year-month-day print(format(now, '%y-%m-%d')) # Current time formatted as short date year-month-day print(format(now, '%Y<%m>%d')) # The current time is formatted as a long date year-month-day with intervals "<" and ">" print(format(now, '%c')) # Local day-of-the-week year-month-day representation print(format(now, '%B')) # Local full month representation, output: May print('It's now the first of the year', format(now, '%j'), 'Heaven') # What day of the year is today, output: It is now the 017th day of the year print('This week is the first of the year', format(now, '%U'), 'Chow') # This week is the second week of the year, output: this week is the 02nd week of the year print(format(now, '%y%m%d')) # Year, month, and day in short date format with no separator, output: 210117 print(format(now, '%Y-%m')) # Long date format year-month, output: 2021-01 print(format(now, '%m-%d')) # Month-Day display, output: 01-17 print(format(now, '%m')) # Months displayed separately, output: 01 print(format(now, '%d')) # Date displayed separately, output: 17 print(format(now, '%H%M%S')) # No spacer, output: 133536 print(format(now, '%H:%M:%S')) # Standard hours-minutes-seconds, output: 13:35:36 print(format(now, '%I:%M:%S %I')) # 12-hour time-minute-second, output: 01:35:36 01 print(format(now, '%H:%M')) # Hours + minutes, output: 13:35 print(format(now, '%M%S')) # minutes + seconds, output: 3536 print(format(now, '%H')) # Hours only, output: 13 print(format(now, '%H:%M:%S %p')) # Date display by AM, PM display, output: 13:35:36 PM print(format(now, '%a')) # English week abbreviation, output: Sun print(format(now, '%A')) # English week full display, output: Sunday week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] print(week[int(format(now, '%w'))]) # Chinese week, output: Sunday dt = (2020, 5, 9) dm = (2020, 5, 9, 12, 50, 20) # Input dates formatted by year-month-day and time, processed as 0 hours because time was not entered print(format(dt, '%Y-%m-%d %H:%M:%S')) print(format(dt, '%Y-%m-%d')) # Format the entered date in year-month-day format print(format(dm, '%Y-%m-%d %H:%M:%S')) # Format the date entered in terms of year-month-day and time print(format(dm, '%Y-%m-%d')) # Format the entered date in year-month-day format wx = () print(str(wx), format(1, '0>3')) # Year-Month-Day + 3-digit numbering print(format(now, '%Y-%m-%d'), format(1, '0>3')) # Year-Month-Day + 3-digit numbering print(format(now, '%Y%m%d'), 'NO' + format(1, '0>3')) # Year-Month-Day + NO + 3 digit number print(format(now, '%d'), 'NO' + format(1, '0>3')) # Date + NO + 3 digit number print(format(now, '%H%M'), 'NO' + format(1, '0>3')) # clocks+ingredient +NO+3bit number
Using the f-string method
f-string is a new string formatting method introduced in Python 3.6. Since there are many different ways to format strings that are similar to the ones described earlier, here's a simple example that demonstrates its usage.
Example 1: Embedding Variables and Expressions in Strings with f-string Methods
name = "Python" # String ver = 3.6 # Floating point # Output: Python-3.6, Python-3.7, Python-3.8000000000000003 print(f"{name}-{ver}、{name}-{ver + 0.1}、{name}-{ver + 0.2}")
[Example 2] In Example 1, an overflow occurs when an expression calculates a floating-point number, and a special formatting modifier can be used to limit the display to only 1 decimal place.
name = "Python" # String ver = 3.6 # Floating point # Output: Python-3.6, Python-3.7, Python-3.8 print(f"{name}-{ver}、{name}-{ver + 0.1}、{name}-{ver + 0.2:.1f}")
[Example 3] Convert the hexadecimal number 10 into decimal, hexadecimal, octal, and binary representations, respectively.
n = 0x10 # Hexadecimal number 10 # Output: dec:16, hex:10, oct:16, bin:10000 print(f"dec:{n:d}, hex:{n:x}, oct:{n:0}, bin:{n:b}")
If you want to represent a string on multiple lines, you can use the following example to precede each substring with the f modifier.
name = "Python" # String ver = 3.6 # Floating point s = f"{name}-" \ f"{ver}" print(s) # exports:Python-3.6
To this point, this article on the most detailed Python formatting output usage to explain the article is introduced to this, more related Python formatting output usage content please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!