Differences between formatted string% and format two methods in Python

Source: Internet
Author: User

Tag: Attribute parameter class his code href specify attribute list

Python2.6 introduced a format formatted string method, now there are two ways to format the string, that is,% and format, what is the difference between the two methods? Please see the following resolution.

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

In general, using% is sufficient to meet our needs, but it is best to choose the format method if you want to add elements or list types to a location like this.

New features

Added f-strings to Python3.6:

" Q1mi " in[2]: Age =in[3]: F'My name is {name}. I ' m {age}"out["My name is Q1mi.i ' m "
Common methods for format

By Location (index)

IN[1]: data = ["q1mi",]in["name:{0}, age:{1}". Format (*data) out['name:q1mi, age:18'


by keyword

IN[1]: data = {"name""Q1mi" "Age" :}in["name:{name}, age:{age}". Format (* *data) out['  name:q1mi, age:18'

Through object properties

IN[1]:classPerson (Object): ...:def __init__(self, Name, age): ...: Self.name=name ...: self.age=Age ...:def __str__(self): ...:return "This was {self.name}, {self.age}, years old.". Format (self=Self ) ...: in[2]: p = person ("Q1mi", 18) in[3]: str (p) out[3]:'This was q1mi, years old.'


by subscript

" {0[0]} is {0[1]} years old. " . Format (data) out['q1mi is the years old. '

Fill and align

Padding is used in conjunction with alignment

^ < > is centered, left-aligned, right-aligned, followed by width.

: The filled character after the number, only one character, not specified by default is filled with spaces.

IN[1]:"{: >10}". Format (' -') out[0][' -'in[2]:"{: 0>10}". Format (' -') out[2]:'0000000018'in[3]:"{: a>10}". Format (' -') out[3]:'AAAAAAAA18

Add a string that comes with the Zfill () method:

The Python Zfill () method returns a string of the specified length, the original string is right-aligned, and the front padding is 0.

Zfill () method Syntax: Str.zfill (width)

Parameter width Specifies the length of the string. Original string right-aligned, front padding 0

Returns a string of the specified length

" {:. 2f} ". Format (3.1415926) out['3.14'


Accuracy and type F

Accuracy is often used in conjunction with Type F.

" {:. 2f} ". Format (3.1415926) out['3.14'

Where. 2 represents a precision of 2 length, and F represents a float type.

Other binary

b d o x are binary, decimal, octal, hexadecimal, respectively.

IN[1]:"{: b}". Format (18) out[0]['10010'in[2]:"{:D}". Format (18) out[2]:' -'in[3]:"{: o}". Format (18) out[3]:' A'in[4]:"{: x}". Format (18) out[4]:' A'

Thousands separator

" {:,} ". Format (1234567890) out['1,234,567,890'

Differences between formatted string% and format two methods in Python

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.