Home > Article > Backend Development > Summary of common formatting string methods in Python (percent sign and format method)
1. Percent sign (%) method, C-like printf, needs to be of different types.
1. Anonymous tuple. (Recommended to be used when there are few parameters)
>>> 'Name: %s, Age: %d' % ('walker', 99)
'Name: walker, Age: 99'
2. Naming dict , dictionary keys can be reused.
>>> 'Name: %(name)s, age: %(age)d, length of service: %(age)d' % {'name':'walker', 'age':99}
'Name: walker, age: 99, length of service: 99'
2. Format function, there is no need to specify string or numeric type.
1. Anonymous parameters.
>>> 'Name: {0}, Age: {1}'.format('walker', 99)
'Name: walker, Age: 99'
2. Named parameters, parameters can be reused. (Recommended when there are many parameters)
>>> 'Name: {name}, Age: {age}, Length of service: {age}'.format(name='walker', age=99)
'Name :walker, age: 99, length of service: 99'