Description of str. format () in Python

Source: Internet
Author: User
This article mainly introduces str in python programming. the basic syntax and advanced usage of format () are very detailed with examples. I hope you will like this article to introduce str in python programming in detail. the basic syntax and advanced usage of format () are very detailed with examples.

1. str. format introduction

In Python, we can use + to connect strings. in simple cases, this method works well. However, when we need to perform a complex string connection, if we still use + to complete it, it will not only make the code obscure, but also make the code difficult to maintain, at this point, this method seems powerless.

For example, we want to print such a record:

User: John has completed Action: payment at Time: 13: 30: 00

If the plus sign is used, the following form is used:


print "User:" + user_name + " has completed Action:" + \       action_name + " at Time:" + current_time

If we look back at this code later, it is difficult to intuitively see its output format, and it is relatively difficult to modify it.

We can use % to achieve this:


print "User:%s has completed Action:%s at Time:%s" % \     (user_name, action_name, current_time)

This code is much clearer and more concise.

However, Python provides us with another simple and elegant implementation method, which is also officially recommended: use str. format () to format strings:


print "User:{} has completed Action:{} at Time:{}".format(     user_name, action_name, current_time)

Str. format can be used in both simple scenarios and complex string replacement without tedious string connection operations. Both the built-in str and unicode types of Python support using str. format () to format strings.

Next we will discuss in detail the specific usage of str. format.

2. str. format Basic syntax

The formatted string uses braces {} to enclose the replacement field, that is, the string to be replaced. Characters not enclosed by curly brackets will appear in the results.

2.1. Use Location Index

The following two statements are equivalent:

"Hello, {}and {}! ". Format (" John "," Mary ")

"Hello, {0} and {1 }! ". Format (" John "," Mary ")

You can write or omit the index of the target string in curly braces. If this parameter is omitted, it is replaced by the target string in the format brackets in sequence.

2.2. use keyword index

In addition to specifying the target string by position, we can also specify it by keyword.

For example:


"Hello, {boy} and {girl}!".format(boy="John", girl="Mary")

The advantage of using the keyword index is that we don't need to care about the parameter location, and the final result of the string can be clear at a glance. In future code maintenance, we can quickly modify the corresponding parameters without looking for the corresponding parameters against the strings.

Note: If the string itself contains curly braces, you must repeat it twice to escape it. For example, the string itself contains {. to let Python know that this is a common character, rather than braces used to enclose and replace fields, we only need to rewrite it.

3. str. format advanced syntax

Str. format is powerful enough to complete the formatting output encountered in daily work. Mastering this method can lay a good foundation for future string processing and save a lot of time.

3.1. access parameter attributes or elements

When str. format is used to format a string, we usually pass the target string as a parameter to the format method. In fact, we can also access a property or element of a parameter in a formatted string:

"My car is {0. color}.". format (black_car)
"The first student is {student [0]}.". format (student = stu_list)
"John is {d [john]} years old.". format (d = age_dict)

3.2. parameter output conversion

The parameter string output is implemented by its own format method by default. That is to say, Python replaces the field with the format output of the parameter. If you want to call str () or repr () to convert the parameters, you can add the conversion flag:


# call str() on argument"It's a {0!s}."#call repr() on argument"We can get info from {name!r}."

4. str. format

The format of the formatted string is as follows:

"... {Field_name! Conversion: format_spec }..."

From the code above, the formatted string can be divided into three parts: field_name, conversion, and format_spec, which correspond to the field name (index), conversion mark, and format description. The field name is mandatory, and the latter two are optional. The conversion mark is followed by an English exclamation point, and the format description is followed by an English colon.

As mentioned above, the field name is both a location index and a keyword index. After a field name, you can click to access the attribute or use square brackets to access the element.

Here, we will focus on format_spec.

The format description contains six options: fill, align, sign, width, precision, and type. Their positional relationships are as follows:

[[Fill] align] [sign] [#] [0] [width] [,] [. precision] [type]
Fill
It can be any character. the default value is space.

Align
Valid only when the minimum width is specified.

<Left alignment (default)
> Right alignment
= Valid only for numbers; place the filled characters between symbols and numbers, for example, + 0001234
^ Center alignment
Sign
Valid only for numbers

+ All numbers are signed
-Only negative numbers with symbols (default option)
That is, space. positive numbers are preceded by spaces and negative numbers are preceded by symbols.
'#'
Valid only for integers

The corresponding 0b, 0o, and 0x values are automatically added before binary, octal, and hexadecimal values.

','
A separator is automatically added between every three numbers.

Width
Decimal number, which defines the minimum width. If not specified, it is determined by the width of the content.

If align is not specified, you can add a value of 0 before width to achieve automatic filling of 0, which is equivalent to setting fill to 0 and align to =.

Precision
Used to determine the precision of a floating point or the maximum length of a string. It cannot be used as an integer.

Type
Determines the parameter type. the default value is s, which is a string.

Integer output type:

B: output in binary format
C: converts an integer to a corresponding unicode character.
D: output in decimal format (default)
O: output in octal
X: lowercase output in hexadecimal format
X: in hexadecimal format.
N: it is the same as d, but it uses the separator of the current environment to separate every 3 digits

Decimal floating point output type:

E: exponential tag, which is output by scientific notation and expressed by e. The default precision is 6.
E: same as e, but uppercase E is used to represent the exponential part.
F: outputs a value as a fixed point. The default precision is 6.
F: same as f
G: general format. for a given precision p> = 1, take the p-bit valid number of the value and output it by fixed point or scientific notation (default)
G: The general format. it is the same as g. When the value is too large, E is used to represent the exponential part.
N: it is the same as g, but it uses the separator of the current environment to separate every 3 digits
%: Percentage flag. The value is output as a percentage and the f flag is set.

The above is a detailed description of str. format () in Python. For more information, see other related articles in the first PHP community!

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.