Summary of formatting methods for strings in Python

Source: Internet
Author: User
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])


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.