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.
Recommended learning: Python learning tutorial
Detailed explanation of format
1. Basic usage
- 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("乒乓球","羽毛球","敲代码"))#我喜欢乒乓球和羽毛球。""" 花括号多于参数的个数,则会报错。 """
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("海绵宝宝","机器猫","海贼王","火影忍者","龙珠")) #小明喜欢机器猫,海贼王,和海绵宝宝
3. Use keywords to pass
print("我今年{age}岁,我在读{college}".format(age=18","college="大学")) #我今年18岁,我今年20岁#关键字可以随便放置print("我今年{age}岁,我在读{college}".format("college="大学",age=18"))
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  '''
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))""" 我是卡卡罗特,是孙悟空,但不可改变的是我是正义的战士。 """
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))
#传递关键字print("我是{p.name},家在{p.addr}".format(p=p))print("我是{girl.name},家在{girl.addr}".format(girl=p))""" 我是孙悟空,家在包子山。 我是孙悟空,家在包子山。 """
2.4 Usage of square brackets
mylist=["陈道明","www.chendaoming.cc"]print("网站名:{0[0],地址{0[1]}}".format(my_list))
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 " """
#正号表示正数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%
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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software