Home Backend Development Python Tutorial Detailed explanation of str.format() in Python

Detailed explanation of str.format() in Python

Mar 13, 2017 am 09:22 AM
python

This article mainly introduces to you in detail the basic syntax and advanced usage of str.format() in pythonProgramming. It is very detailed and comes with examples. I hope you can Like

1. The introduction of str.format

In Python, we can use + to connect strings, in simple In this case this method can work well. But when we need to perform complex string concatenation, 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 time, this method becomes insufficient.

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 we go back and read this code in the future, it will be difficult for us Its output format can be seen intuitively, and it is 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 can also perform 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 #. 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 format string is as follows:

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


As you can see from the above code, the format 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
'#'
Only valid for integers

Automatically add corresponding 0b, 0o, 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

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles