Home > Backend Development > Python Tutorial > Detailed explanation of the basic syntax and advanced usage of str.format()

Detailed explanation of the basic syntax and advanced usage of str.format()

Y2J
Release: 2017-05-15 10:48:43
Original
4600 people have browsed it

This article mainly introduces to you the basic syntax and advanced usage of str.format() in python programming. It is very detailed and comes with examples. I hope you will like it

1. The introduction of str.format

In Python, we can use + to connect strings. This method can work well in simple cases. But when we need to perform complex string concatenation, if we still use + to complete it, it will not only make the code obscure and difficult to understand, but also make the code difficult to maintain. In this case, this method It seems that he is unable to do what he wants.

For example, we want to print a record like this:

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

If you use the plus sign to implement it, it will be in the following form:

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

If you go back and read this code in the future, it will be difficult for us to intuitively see its output format, and It is also relatively troublesome to modify.

We can use % instead:

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

This time the code becomes much clearer and more concise.

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

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

str.format can be used in simple scenarios and is also capable of complex string replacement without cumbersome string concatenation operations. Python's built-in types str and unicode both support the use of str.format() to format strings.

We will discuss the specific usage of str.format() in detail next.

2. Basic syntax of str.format

The formatted string uses curly braces {} to surround the replacement field, which is the string to be replaced. Characters not surrounded by curly braces will appear intact in the result.

2.1. Using position Index

The following two ways of writing are equivalent:

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

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

Inside the curly braces The index of the target string can be written or omitted. If omitted, replacement is performed in the order of the target strings enclosed in format brackets.

2.2. Using keyword index

In addition to specifying the target string through position, we can also specify it through keywords.

For example:

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

The advantage of using keyword index is that we do not need to care about the position of the parameters, and the final result of the string can be seen at a glance. In future code maintenance, we can quickly modify the corresponding parameters without having to search for the corresponding parameters one by one against the string.

Note: If the string itself contains curly braces, you need to repeat them twice to escape them. For example, if the string itself contains {, to let Python know that this is a normal character and not the curly braces used to surround a replacement field, we simply rewrite it as {{.

3. str.format advanced syntax

str.format is very powerful, enough to complete the formatted output## encountered in daily work #. Being proficient in this method can lay a solid foundation for future string processing and save a lot of time.

3.1. Access the

attribute of the parameter or element

When using str.format to format a string, we usually pass the target string as a parameter to the format method . In fact, we can also access an attribute or element of the parameter in the format 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 string output of parameters is implemented by its own format method by default. That is, Python uses the format output of the parameter in place of the replacement field. If we want to call str() or repr() to convert parameters, we can do so by adding a conversion flag:

# call str() on argument
"It's a {0!s}."

#call repr() on argument
"We can get info from {name!r}."
Copy after login

4. str.format general form

The general form of the formatted string is as follows:

"... {field_name!conversion:format_spec} ..."


As you can see from the above code, the format The transformation string can be divided into three parts: field_name, conversion, and format_spec, which respectively correspond to the replacement field name (index), conversion flag, and format description. Among them, the field name is required, while the latter two are optional. The conversion flag follows the exclamation point, and the format description follows the colon.

As mentioned before, the field name can be either a position index or a keyword index. Field names can be followed by dots to access attributes, or square brackets to access elements.

Here, we focus on the format description (format_spec).

The format description contains 6 options, namely fill, align, sign, width, precision, and type. Their positional relationship is as follows:

[[fill]align][sign][#][0][width][,][.precision][type]
fill
can be anything character, default is space.

align
Only valid when minimum width is specified.

< Left justified (default option)
> Right justified
= Valid only for numbers; place padding characters between symbols and numbers, for example +0001234
^ Center aligned
sign
Only valid for numbers

+ All numbers are signed
- Only negative numbers are signed (default option)
That is, spaces; positive numbers are preceded by spaces, and negative numbers are preceded by spaces Signed
'#'
is only valid for integers

Automatically add the corresponding 0b, 0o, and 0x before binary, octal, and hexadecimal values.

','
Automatically add a , separator between every three numbers.

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

If the alignment (align) is not specified, you can add a 0 in front of width to automatically fill 0, which is equivalent to setting fill to 0 and align to =.

precision
Used to determine the precision of floating point numbers, or the maximum length of a string. Not available for integer values.

type
Determine the parameter type, the default is s, which is a string.

Integer output type:

b: Output in binary format
c: Convert the integer into the corresponding unicode character
d: Output in decimal (default option)
o: Output in octal
x: Output in hexadecimal lowercase
X: Output in hexadecimal uppercase
n: Same as d, but use the current environment's delimiter to separate every 3 bits Number

Decimal floating point number output type:

e: exponent mark; output using scientific notation, using e to represent the exponent part, the default precision is 6
E: and e is the same, but uppercase E is used to represent the exponent part
f: Output the value in fixed-point form, the default precision is 6
F: The same as f
g: General format; for the given precision p > = 1, take the p-digit significant digits of the value, and output it in fixed-point or scientific notation (default option)
G: general format; the same as g, use E to represent the exponent part when the value is too large
n : Same as g, but uses the delimiter of the current environment to separate each 3-digit number
%: Percent mark; use the percentage form to output the value, and set the f mark

[Related recommendations]

1. Special recommendation: "php Programmer Toolbox" V0.1 version download

2. Python free video tutorial

3. Python object-oriented video tutorial

The above is the detailed content of Detailed explanation of the basic syntax and advanced usage of str.format(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template