python's simple use of format

Shared a few days ago A script for displaying progress bars The format method is used.

Explain briefly about Script The usage of format in the script and several format usages commonly used in the script.

1. Form usage of percentage display in script:

# coding:utf-8
'''
Note:
   Format usage
Author:Qred
Date:2019/9/14
'''

# format usage
progress_bar_num = 'First parameter'
percentage = 0.4589
# The second parameter length is5,Accurate to decimal point number0
result = '{0} {1:>5.0%}'.format(progress_bar_num, percentage)
print result
# The second parameter is the default length, accurate to the decimal point number.0
result = '{0} {1:>.0%}'.format(progress_bar_num, percentage)
print result
# The second parameter length is5,Accurate to decimal point number0
result = '{0} {1:%}'.format(progress_bar_num, percentage)
print result
# The second parameter is accurate to the decimal point.3position
result = '{0} {1:.3%}'.format(progress_bar_num, percentage)
print result
# The second parameter length is6,Accurate to decimal point3position
result = '{0} {1:>6.3%}'.format(progress_bar_num, percentage)
print result
# The second parameter length is9,Accurate to decimal point3Bit, spare bit P Fill
result = '{0} {1:P>9.3%}'.format(progress_bar_num, percentage)
print result
# The second parameter length is9,From left to right, exactly after decimal point3Bit, spare bit P Fill
result = '{0} {1:P<9.3%}'.format(progress_bar_num, percentage)
print result
# The second parameter length is9,Centrally aligned, precise to the decimal point3Bit, spare bit P Fill
result = '{0} {1:P^9.3%}'.format(progress_bar_num, percentage)
print result

Output results:

2. When format has multiple parameters, you can refer to the following usage:

# Use of parameters:
# Use in order of parameters
result = '{} {}'.format(progress_bar_num, percentage)
print result
# Specify in order
result = '{1} {0}'.format(progress_bar_num, percentage)
print result
# Specified name
result = '{progress_bar_num} {percentage}'.format(progress_bar_num = progress_bar_num, percentage = percentage)
print result

Output results:

3. When the parameter type passed is list or dictionary:

# There are also ways to pass list and dictionary type parameters:
list = [22,23]
print '{0[0]},{0[1]}'.format(list)
dicts = {'key':'value'}
print '{key}'.format(**dicts)

Output results:

4. Number format of specified parameters

# Prefabricated formats for specified values
number = 99
print  'Decimal system:{:d}'.format(number)
print  'Binary:{:b}'.format(number)
print  'Octal number system:{:o}'.format(number)
print  'Hexadecimal:{:x}'.format(number)

Output results:

Posted by AL-Kateb on Mon, 30 Sep 2019 09:24:58 -0700