Home  >  Article  >  Backend Development  >  A brief analysis of the usage of Python’s format

A brief analysis of the usage of Python’s format

WBOY
WBOYforward
2022-02-28 17:30:434573browse

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("乒乓球","羽毛球","敲代码"))#我喜欢乒乓球和羽毛球。"""
花括号多于参数的个数,则会报错。
"""

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
![A brief analysis of the usage of Python’s format](https://img-blog.csdnimg.cn/20210321105132614.png#pic_center)
'''

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

A brief analysis of the usage of Python’s 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%

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:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete