Table of Contents
Detailed explanation of format
1. Basic usage
2. Sublimation explanation
2.1 Use of compound field names
2.2 Use of dot number
2.4 Usage of square brackets
2.5 Aligning strings
Home Backend Development Python Tutorial A brief analysis of the usage of Python's format

A brief analysis of the usage of Python's format

Feb 28, 2022 pm 05:30 PM
python

This article brings you python related knowledge, which mainly introduces the usage of format. fotmat is Python's format string function, mainly through the curly braces {} in the string. , to identify the replacement field and complete the formatting of the string. I hope it will be helpful to everyone.

A brief analysis of the usage of Python's format

Recommended learning: Python learning tutorial

Detailed explanation of format

1. Basic usage

  1. format terminology explanation
    fotmat is Python's format string function. It mainly identifies replacement fields through the curly braces {} in the string, thereby completing the formatting of the string.
print("我叫{},今年{}岁。".format("小蜜",18))#我叫小蜜,今年18岁。#花括号的个数决定了,参数的个数。但是花括号的个数可以少于参数。print("我喜欢{}和{}"format("乒乓球","羽毛球","敲代码"))#我喜欢乒乓球和羽毛球。"""
花括号多于参数的个数,则会报错。
"""
Copy after login

2. Pass in positional parameters through numeric parameters
Please note the following when passing in parameters

  • The number must be an integer greater than 0
  • Replacement fields with numbers can repeat
  • A simple field name in the form of numbers is equivalent to treating the field as a sequence. Get values ​​one by one in the form of index
#通过数字索引传入参数print("名字{0},家住{1}").format("橙留香","水果村")
#带数字的替换1字段可以重复"pythonprint("我爱{0}。\n他爱{1}。\n{0}爱{1}".format("灰太狼","红太狼")"""
我爱灰太狼
他爱红太狼
灰太狼爱红太狼
""""""
数字形式的简单字段名相当于把字段当成一个序列形式。通过索引的形式进行一一取值
"""print("小明喜欢{1},{2}和{0}".foramt("海绵宝宝","机器猫","海贼王","火影忍者","龙珠"))
#小明喜欢机器猫,海贼王,和海绵宝宝
Copy after login

3. Use keywords to pass

print("我今年{age}岁,我在读{college}".format(age=18","college="大学"))
#我今年18岁,我今年20岁#关键字可以随便放置print("我今年{age}岁,我在读{college}".format("college="大学",age=18"))
Copy after login

4. Mixed use of keywords and numbers
Note the following

  • #Number and key fields can be mixed to pass parameters
  • Keyword parameters must come after positional parameters.
  • When used in a mixed manner, numbers can be omitted
  • Omitting field names {} cannot be used together with numeric field names
#混合使用传递参数print("我是要当{0},他是要当{1},这个世界只有一个{truth}".format("海贼王","火影",truth="真理"))
#我要当海贼王,他要当火影,这个世界只有一个真理
#数字也可以省略print("我是要当{},他是要当{},这个世界只有一个{truth}".format("海贼王","火影",truth="真理"))
#如果关建字位于位置参数之前则会发生'''
SyntaxError: unexpected indent
![A brief analysis of the usage of Pythons format](https://img-blog.csdnimg.cn/20210321105132614.png#pic_center)
'''
Copy after login

5. Use tuples and dictionaries Passing parameters

  • format can use tuple and dictionary to pass parameters, and the two can be mixed
  • when used in various combinations. Positional parameters should be in front of keyword parameters, and tuples should be in front of dictionary
a=["鸣人","火影","雏田"]print("我是{},我是要当{}的男人".format(*a))"""
我是鸣人,我是要当火影的男人
"""print("我是{1},我是要当{2}的男人".format(*a))
#使用字典传参v={"name":"孙悟空","skill":"龟派气功"}print("我是{name},我的绝招是{skill}".format(**v))"""
我是孙悟空,我的绝招是龟派气功
"""#同时使用元组和字典传参name=["卡卡罗特","界王拳"]names={"nickname":"孙君","skill":"元气弹"}print("我是{0},我的绝招是{skill}".format(*name,**names))print("我是{nickname},我的绝招是{1}".format(*name,**names))#同时使用位置参数,元组,关键字参数,字典传参。#注意位置参数要在关键数参数前面a=["卡卡罗特"]dic={"name":"超级赛亚人"}print("我是{0},我也是{0},因为我是正义的战士,所以我变成了{name}".format("卡卡罗特",*a,**dic))"""
我是卡卡罗特,是孙悟空,但不可改变的是我是正义的战士。
"""
Copy after login

2. Sublimation explanation

2.1 Use of compound field names
  • format uses two forms: numbers and variable names. This is the compound field
  • The compound field name supports two operators
    - [] square brackets
    - . Dot number
2.2 Use of dot number
class Person:
	def __int__(self,name,addr):
		self.name=name
		self.addr=addr
p=Person("孙悟空","包子山")
#点号用法。传递位置参数。print("我是{0.name},家在{0.addr}".format(p))
#当只有一个字段的时候,就可以省略数字print("我是{.name}}".format(p))
#试一下传递文件对象的属性f=open("out.txt","w")print("文件名为:"{.name}.format(f))
Copy after login
#传递关键字print("我是{p.name},家在{p.addr}".format(p=p))print("我是{girl.name},家在{girl.addr}".format(girl=p))"""
我是孙悟空,家在包子山。
我是孙悟空,家在包子山。
"""
Copy after login

2.4 Usage of square brackets

mylist=["陈道明","www.chendaoming.cc"]print("网站名:{0[0],地址{0[1]}}".format(my_list))
Copy after login

2.5 Aligning strings

  • ^ In the play, the width of the following band
  • Right-aligned and followed by the width

  • : The character followed by padding can only be one character. If not specified, it will be filled with spaces by default
print("{:>5}".format(1))#宽度为5,右对齐print(":>5".format(10))print(":>5".format(100))print(":>5".format(1000))"""
输出结果为	
	1	 
	10
	100
	1000		 "
"""
Copy after login

A brief analysis of the usage of Pythons format

#正号表示正数print("{:+2f}".format(3.14))#+3.140000print("{:-2f}".format(-1))
#-1.000000#不带小数的print("{:.0f}".format(3.23123131))
#3#以逗号为分隔符的print("{:,}".format(100000))
#100,000#表示一个百份比print("{:.2%}".format(0.25))
#25%
Copy after login

Recommended learning: python video tutorial

The above is the detailed content of A brief analysis of the usage of Python's format. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

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.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

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.

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