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

Summary of formatting methods for strings in Python

高洛峰
高洛峰Original
2017-03-06 13:37:331285browse

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)


Multiple replacement values:

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

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)

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)

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


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])


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

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