Python字符串格式化 format()

时间:2020-02-23 14:43:26  来源:igfitidea点击:

Python String format()函数用于根据模板字符串和提供的值创建格式化的字符串。

Python字符串format()

Python字符串format()函数语法为:

str.format(*args, **kwargs)
  • 模板字符串可以是字符串文字,也可以包含使用" {}"作为分隔符的替换字段。

  • 替换字段可以是所提供参数的数字索引,也可以是基于关键字的参数。

  • 如果替换字段没有索引或者关键字值,则根据索引并按顺序替换它们,即0,1,…,n。

  • 我们可以提供诸如元组和列表之类的序列作为基于索引的替换的参数。

  • 我们可以提供字典作为基于关键字的替换的参数。

  • format函数参数也可以是一个对象,我们可以使用点运算符来替换字段的属性。

  • 我们可以使用format()函数创建一个指定长度的字符串,该字符串的字面量为右,左或者中心对齐。
    我们还可以指定用于填充的字符,默认为空白。

  • 字符串format()函数提供了许多格式化数字的功能。
    例如,从十进制到八进制,十六进制等的基本转换。
    我们还可以执行百分比,填充等。

  • 有一些快捷方式可以使用!s和!r在参数上调用__str __()和__repr __()函数。

Python字符串format()示例

让我们看一些使用format()函数的示例。

基于简单索引的格式

print("My Name is {0}".format("hyman"))

print("I like {0} and {1}".format("Java", "Python"))
# same as above
print("I like {} and {}".format("Java", "Python"))

# index can be in any order
print("I like {1} and {0}".format("Java", "Python"))

输出:

My Name is hyman
I like Java and Python
I like Java and Python
I like Python and Java

序列作为format()参数

# unpacking from sequences
t = ("Java", "Python")
print("I like {1} and {0}".format(*t))

l = ["Java", "Python"]
print("I like {} and {}".format(*t))

输出:

I like Python and Java
I like Java and Python

格式为()的关键字参数

print("{name} is the {job} of {company}".format(name="hyman", job="CEO", company="theitroad"))

输出:hyman是theitroad的首席执行官

字典作为format()参数

我们可以在format()函数参数中使用基于字典的关键字替换字段。

d = {"name": "hyman", "job": "CEO", "company": "theitroad"}
print("{company} {job} is {name}".format(**d))

输出:theitroad CEO是hyman

访问对象属性以进行字段替换

我们可以通过format()方法传递一个对象,并使用点运算符访问其属性以进行字段替换。

class Data:
  id = 0
  name = ''

  def __init__(self, i, n):
      self.id = i
      self.name = n

dt = Data(1, 'Test')

print("{obj_name} id is {obj.id} and name is {obj.name}".format(obj_name="Data", obj=dt))

输出:"数据ID为1,名称为Test"

带填充和对齐的格式化字符串

我们可以使用format()方法创建一个指定长度的字符串。
默认情况下,它将保持左对齐,并且空白将用于填充。
但是,我们可以指定用于填充和对齐源字符串的字符。

>>> "{:^30}".format("data center aligned")
'     data center aligned      '

>>> "{:30}".format("data without align")
'data without align            '

>>> "{:<30}".format("data left aligned")
'data left aligned             '

>>> "{:>30}".format("data right aligned")
'            data right aligned'

>>> "{:^30}".format("data center aligned")
'     data center aligned      '

>>> "{:|^30}".format("data with fill character")
'|||data with fill character|||'

我在此示例中使用的是Python控制台,因此您可以看到字符串中的空白填充。
如果我们在这里使用print()函数,则不会显示字符串周围的引号,并且字符串长度也不清楚。

带数字的字符串format()

数字有许多格式设置选项,让我们看一下其中的一些。

为格式化的字符串指定符号(+,-)

print('{:+f}; {:+f}'.format(1.23, -1.23))
print('{: f}; {: f}'.format(1.23, -1.23))
print('{:-f}; {:-f}'.format(1.23, -1.23))

输出:

+1.230000; -1.230000
 1.230000; -1.230000
1.230000; -1.230000

请注意,在第二条语句中,空格被用作数字的前缀。
对于负数,始终使用负号(-)。

将整数格式化为不同的底数

我们可以轻松地将int转换为不同的基数,例如十六进制,八进制,二进制等。
我们还可以指定格式化的字符串是否包含基数的前缀。

print("int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(28))
print("int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(0x1c))
print("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(28))

输出:

int: 28;  hex: 1c;  oct: 34;  bin: 11100
int: 28;  hex: 1c;  oct: 34;  bin: 11100
int: 28;  hex: 0x1c;  oct: 0o34;  bin: 0b11100

带复数的format()

complex_number = 4 + 2j
print("Real: {0.real}, Imaginary: {0.imag}".format(complex_number))

输出:Real:4.0,Imaginary:2.0

就像访问对象的属性一样。

使用逗号作为千位分隔符格式化数字

print('{:,}'.format(1234567890))

输出:1,234,567,890

百分比,填充和舍入

print('Percentage: {:.3%}'.format(19/28))
print('{0:7.2f}'.format(2.344))
print('{0:10.2f}'.format(22222.346))

输出:

Percentage: 67.857%
 2.34
22222.35

请注意,小数点后的舍入是根据默认舍入规则进行的。
另外,在数字前面进行填充。

调用str()和repr()函数

我们可以分别使用!s!r轻松地为对象调用str()和repr()函数。

print("With Quotes: {0!r}, Without Quotes: {0!s}".format("Data"))

class Test:

  def __str__(self):
      return 'test str'

  def __repr__(self):
      return 'test repr'

print("Test Representation: {0!r}, Test String Representation: {0!s}".format(Test()))

输出:

With Quotes: 'Data', Without Quotes: Data
Test Representation: test repr, Test String Representation: test str