Old fashioned
Before Python2.6, the format string was used in a relatively simpler way, although the number of parameters it could receive was limited. These methods are still valid in Python3.3, but there are implicit warnings that these methods will be completely phased out, and there are no clear timelines for the time schedule.
To format a floating-point number:
PI = 3.14159print ("PI =%1.2f",% pi)
Multiple replacement values:
S1 = "Cats" s2 = "Dogs" s3 = "%s and%s living together"% (S1, S2)
There are not enough parameters:
Using the old formatting method, I often made the mistake of "typeerror:not enough arguments for formating string" because I counted the number of substitution variables incorrectly, and it was easy to omit the variables by writing code like this.
Set = (%s,%s,%s,%s,%s,%s,%s,%s) "% (a,b,c,d,e,f,g,h,i)
For a new Python format string, you can use the numbered parameter, so you don't need to count the number of arguments.
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 was% (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 (motto=3.14, food=[1,2,3])