Python string formatting tool

   in Python, there are two string formatting schemes. One is the% operator that existed before Python 2.6, and the other is a new format string function str.format() from Python 2.6.

    

catalogue

%Formatting tool

  students who are familiar with the printf() function of C language will easily learn the% formatting tool. The print() function formats and outputs various types of data using conversion specifiers starting with%:

Integer output:

  • %o -- oct octal
  • %d -- dec decimal
  • %x -- hex hex

Output of floating point numbers:

  • %f - retain six significant digits after the decimal point 3f, 3 decimal places reserved
  • %e - retain six significant digits after the decimal point and output in exponential form 3e, keep 3 decimal places and use scientific counting method
  • %g -- on the premise of ensuring six significant digits, use decimal method, otherwise use scientific counting method. --% 3g, keep 3 significant digits and use decimal or scientific counting method

String output:

  • %s -- output string
  • %10s -- right aligned, placeholder 10 bits
  • %-10s -- left aligned, placeholder 10 bits
  • %. 2s -- intercept 2-bit string
  • %10.2s -- 10 bit placeholder, intercepting two bit string
print('%o' % 20)
print('%d' % 20)
print('%x' % 20)


print('%f' % 1.11)  # 6 decimal places are reserved by default
print('%.1f' % 1.11)  # Take 1 decimal place
print('%e' % 1.11)  # The default is 6 decimal places, using scientific counting method
print('%.3e' % 1.11)  # Take 3 decimal places and use scientific counting method
print('%g' % 1111.1111)  # Default 6 significant digits
print('%.7g' % 1111.1111)  # Take 7 significant digits
print('%.2g' % 1111.1111)  # Take 2 significant digits and automatically convert them to scientific counting method

print('%s' % 'hello world')  # String output
print('%20s' % 'hello world')  # Align right, take 20 digits, if not enough, fill in the digits
print('%-20s' % 'hello world')  # Align left, take 20 digits, if not enough, fill in the digits
print('%.2s' % 'hello world')  # Take 2 digits
print('%10.2s' % 'hello world')  # Right aligned, 2 digits
print('%-10.2s' % 'hello world')  # Left aligned, 2 digits

# Output:
# 24
# 20
# 14
# 1.110000
# 1.1
# 1.110000e+00
# 1.110e+00
# 1111.11
# 1111.111
# 1.1e+03
# hello world
#          hello world
# hello world         
# he
#         he
# he

format function

str.format() enhances string formatting. The basic syntax is to replace the previous% by {} and:. The format function can accept unlimited parameters, and the positions can be out of order.

Location matching:

  • No number, i.e. "{}"
  • With numerical number, the order can be changed, i.e. "{1}" and "{2}"
  • Keywords, namely "{a}" and "{tom}"

Format conversion:

  • 'b' - binary. The number is output based on 2.
  • 'c' - character. Converts an integer to a corresponding Unicode string before printing.
  • 'd '- decimal integer. The number is output based on 10.
  • 'o' - octal. The number is output based on 8.
  • 'x' - hexadecimal. The numbers are output based on 16, and the digits above 9 are in lowercase letters.
  • 'e' - power sign. Print numbers by scientific counting. Use 'e' for power.
  • 'g' - general format. Output the value in fixed point format. When the value is particularly large, it is printed in power form.
  • 'n' - number. When the value is an integer, it is the same as'd ', and when the value is a floating point number, it is the same as' g'. The difference is that it inserts a number separator according to the locale.
  • '%' – percentage. Multiply the value by 100 and print it in fixed point ('f ') format, followed by a percentage sign.

Left middle right alignment and digit completion:

  • < (defau lt) left alignment, > right alignment, ^ middle alignment, = (only for numbers) complement after the decimal point
  • Take digits "{: 4s}" and "{:. 2f}"
    Code examples and others:
import datetime

print('{} {}'.format('hello', 'world'))  # Without field
print('{0} {1}'.format('hello', 'world'))  # Number with number
print('{0} {1} {0}'.format('hello', 'world'))  # Disorder order
print('{1} {1} {0}'.format('hello', 'world'))
print('{a} {tom} {a}'.format(tom='hello', a='world'))  # With keyword

print('{0:b}'.format(3))
print('{:c}'.format(20))
print('{:d}'.format(20))
print('{:o}'.format(20))
print('{:x}'.format(20))
print('{:e}'.format(20))
print('{:g}'.format(20.1))
print('{:f}'.format(20))
print('{:n}'.format(20))
print('{:%}'.format(20))

print('{} and {}'.format('hello', 'world'))  # Default left alignment
print('{:10s} and {:>10s}'.format('hello', 'world'))  # Align 10 bits left and 10 bits right
print('{:^10s} and {:^10s}'.format('hello', 'world'))  # Take 10 middle alignment
print('{} is {:.2f}'.format(1.123, 1.123))  # Take 2 decimal places
print('{0} is {0:>10.2f}'.format(1.123))  # Take 2 decimal places, align right and take 10 decimal places
print('{:<30}'.format('left aligned'))  # Align left
print('{:>30}'.format('right aligned'))  # Right align
print('{:^30}'.format('centered'))  # Middle alignment
print('{:*^30}'.format('centered'))  # Fill with "*"
print('{:0=30}'.format(11))  # In addition, "=" can only be applied to numbers. This method can be replaced by ">"

print('{:+f}; {:+f}'.format(3.14, -3.14))  # Always show symbols
print('{: f}; {: f}'.format(3.14, -3.14))  # If it is a + number, leave a space in front of it
print('{:-f}; {:-f}'.format(3.14, -3.14))  # -Time display -, and '{: f}; {:f} 'consistent

print('{:,}'.format(1234567890))  # Digit thousands separator

print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.date.today()))  # Date time formatting

# Usage of format
# f"xxxx"
# You can add f before the string to achieve the purpose of formatting, and add an object in {}. This is another form of format:
a = "hello"
b = "world"
c = f"{a} {b}"
print(c)

Extension: String template

string.Template, set a string as a template, and finally get the desired string by replacing variables.

Usage example:

from string import Template

template_string = '$who likes $what'
s = Template(template_string)
d = {'who': 'Tim', 'what': 'Kong Fu'}
s_out = s.substitute(d)
print(s_out)

  experience in software testing, interface testing, automation testing, continuous integration and interview. If you are interested, you can go to 806549072. There will be irregular sharing of test data in the group. There will also be technology giants to exchange technology with peers in the industry

Tags: Python

Posted on Tue, 28 Sep 2021 16:36:30 -0400 by willdk