Home >Backend Development >Python Tutorial >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
2017-02-22 16:40:261653browse

The examples in this article describe common formatting string methods in Python. Share it with everyone for your reference, the details are as follows:

[Method 1] Percent sign (%) method, C-like printf, needs to be of different types.

1. Anonymous tuple. (Recommended when there are few parameters)

>>> '姓名:%s, 年龄:%d' % ('walker', 99)
'姓名:walker, 年龄:99'

2. Name the dict, and the dictionary keys can be reused.

>>> '姓名:%(name)s, 年龄:%(age)d, 工龄:%(age)d' % {'name':'walker', 'age':99}
'姓名:walker, 年龄:99, 工龄:99'

[Method 2] format function, there is no need to specify string or numeric type.

1. Anonymous parameters.

>>> '姓名:{0}, 年龄:{1}'.format('walker', 99)
'姓名:walker, 年龄:99'

2. Named parameters, parameters can be reused. (Recommended when there are many parameters)

>>> '姓名:{name}, 年龄:{age}, 工龄:{age}'.format(name='walker', age=99)
'姓名:walker, 年龄:99, 工龄:99'


For more summary of common Python formatting string methods [Percent sign and format method] please refer to related articles Follow PHP Chinese website!

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