string formatting
1. Percent sign
Common formats:
1 tpl = "i am %s" % "alex" 2 3 tpl = "i am %s age %d" % ("alex", 18) 4 5 tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} 6 7 tpl = "percent %.2f" % 99.97623 8 9 tpl = "i am %(pp).2f" % {"pp": 123.425556, } 10 11 tpl = "i am %.2f %%" % {"pp": 123.425556, }
%s # can take any value
%d # can take an integer value
%f #Print floating point numbers, such as %.2f means take two decimal places
%. #Intercept length, such as %.4s means to intercept a 4-digit string
%% # percent sign
%(pp) # Take the K value in the dictionary
PS:
print('root','x','0','qq',sep=':') # can be output
Second, format formatting
Common formats:
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex') tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex']) tpl = "i am {0}, age {1}, really {0}".format("seven", 18) tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18]) tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) tpl = "i am {:s}, age {:d}".format(*["seven", 18]) tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18) tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) tpl = " numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%} " .format(num=15)
{0} # Take the value of the 0th bit in the parameter
* #The prefix symbol required to take the value in the list
** #The prefix symbol required to take the value in the dictionary
:s # can take any value
:f #Print floating point numbers, such as %.2f means take two decimal places
:b #binary
:o #octal
:d #integer/decimal
:x #hex/lowercase
:X #hex/uppercase
:% #Percentage, last 6 digits by default