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

WBOY
Release: 2022-02-28 17:30:43
forward
4615 people have browsed it

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!

Related labels:
source:csdn.net
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