Home > Backend Development > Python Tutorial > Summary of formatting methods for strings in Python

Summary of formatting methods for strings in Python

高洛峰
Release: 2017-03-06 13:37:33
Original
1306 people have browsed it

Old method

Before Python 2.6, the use of format strings was relatively simple, although the number of parameters it could receive was limited. These methods still work in Python 3.3, but there are implicit warnings that these methods will be completely phased out, and there is no clear timetable yet.

Format floating point number:

pi = 3.14159
print(" pi = %1.2f ", % pi)
Copy after login


Multiple replacement values:

s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)
Copy after login

Not enough arguments:

With the old formatting method, I often made the error "TypeError: not enough arguments for formating string" because I miscounted the number of substitution variables, writing It is easy to miss variables in code like the following.

set = (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)
Copy after login

For the new Python format strings, you can use numbered parameters so you don't need to count how many parameters there are.

set = set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)
Copy after login

Python 2.x Dictionary-based string formatting

"%(n)d %(x)s" %{"n":1, "x":"spam"}
reply = """
Greetings...
Hello %(name)s!
Your age squared is %(age)s
"""
values = {'name':'Bob', 'age':40}
print rely % values
Copy after login


Python 3.x format method formatting

template = '{0},{1} and {2}'
template.format('spam','ham','eggs')

template = '{motto}, {pork} and {food}'
template.format(motto='spam', pork='ham', food='eggs')

template = '{motto}, {0} and {food}'
template.format('ham', motto='spam', food='eggs')

'{motto}, {0} and {food}'.format(42, motto=3.14, food=[1,2,3])
Copy after login


More about strings in Python Please pay attention to the PHP Chinese website for related articles summarizing formatting methods!

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