Home  >  Article  >  Backend Development  >  Summary of common formatting string methods in Python (percent sign and format method)

Summary of common formatting string methods in Python (percent sign and format method)

巴扎黑
巴扎黑Original
2016-12-07 09:28:311653browse

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'

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn