Should I format a string using% or format in Python?

Source: Internet
Author: User

The format string in Python currently has two camps:% and format, which one should we choose?

Since Python2.6 introduced the format-formatted string method, I think the% or format is not a problem at all. Don't believe you look down.

% of disadvantage:

# define a coordinate value c = (+)#  use% to format " enemy Coordinates:%s" % c

The above code obviously throws a typeerror like this:

Typeerror:not all arguments converted during string formatting

Like this kind of formatting needs we need to write the following ugly format:

# define a coordinate value c = (+)#  Use the% ugly formatting ... " enemy Coordinates:%s " % (c,)

There is no problem with format:

# define a coordinate value c = (in.)# format " Enemy Coordinates: {}" using format  . Format (c)

Obviously, the above reason is enough for you to use format for future projects.

Added f-strings to Python3.6:

in[2"q1mi"in[3in[4]: F"  My name is {name}. I ' m {age}"out[4"My name is Q1mi.i ' m"

Should I format a string using% or format in Python?

Related Article

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.