A brief analysis of the usage of Python's format
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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 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 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.

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.

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.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

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.
