Summary of common formatting string methods in Python [percent sign and format method]

高洛峰
Release: 2017-02-22 16:40:26
Original
1501 people have browsed it

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'
Copy after login

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

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

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

1. Anonymous parameters.

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

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

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


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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!