English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of Common String Formatting Methods in Python [Percentage Sign and format Method]

This article describes common string formatting methods in Python. Shared for everyone's reference, as follows:

【Method 1】Percentage (%) method, similar to C's printf, which requires different types separately.

1, Anonymity tuple. (Recommended to use when there are few parameters)

>>> 'Name: %s, Age: %d' % ('walker', 99)
'Name: walker, Age:99

2, Named dict, the key of the dictionary can be reused.

>>> 'Name: %(name)s, Age: %(age)d, Work experience: %(age)d' % {'name':'walker', 'age':99
'Name: walker, Age:99, Work experience:99

【Method Two】format function, no need to specify the string or numeric type.

1, Anonymity parameters.

>>> 'Name: {0}, Age: {1}'.format('walker', 99)
'Name: walker, Age:99

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

>>> 'Name: {name}, Age: {age}, Work experience: {age}'.format(name='walker', age=99)
'Name: walker, Age:99, Work experience:99

Readers who are interested in more content related to Python can check the special topics on this website: 'Summary of Python String Operation Skills', 'Summary of Python URL Operation Skills', 'Summary of Python Image Operation Skills', 'Python Data Structures and Algorithms Tutorial', 'Summary of Python Socket Programming Skills', 'Summary of Python Function Usage Skills', 'Classic Tutorial of Python Entry and Advanced', and 'Summary of Python File and Directory Operation Skills'.

I hope the content described in this article will be helpful to everyone's Python program design.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. The website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report any violations, and provide relevant evidence. Once verified, the website will immediately delete the content suspected of infringement.

You May Also Like