深入理解Python的print format

发布时间:2023-05-20

一、什么是Python的print format

Python的print format是一种处理字符串格式化输出的方法。在计算机编程领域,格式化输出是指将变量和常量按照一定规则有序的输出到屏幕上,使输出结果更加清晰可读。 在Python中,我们可以使用print语句来输出结果,同时也可以使用print format来控制输出的格式,包括字符串、数字、浮点数等多种类型。

二、Python中的print format格式化方式

Python中的print格式化方式主要包括传统的使用“百分号(%)法”和使用“花括号({})法”的方法。

1. 使用“百分号”格式化方法

# 示例代码
name = "Tom"
age = 25
print("My name is %s, and my age is %d." % (name, age))

在使用“百分号”(%)格式化方法时,我们需要在字符串中加入格式化指令,例如%s表示字符串,%d表示整型,%f表示浮点数等。 然后我们将要输出的变量依次放到括号()中,作为对应格式化指令的参数,以逗号分隔。 例如上面的示例,输出结果为:My name is Tom, and my age is 25.

2. 使用“花括号”格式化方法

# 示例代码
name = "Tom"
age = 25
print("My name is {0}, and my age is {1}.".format(name, age))

在使用“花括号”({})格式化方法时,我们同样需要在字符串中加入格式化指令,不同的是用花括号{}来代替%。 我们可以使用大括号内的数字来对应传入的变量的位置。 例如上面的示例,输出结果为:My name is Tom, and my age is 25

三、Python中的print format高级应用

在Python中,格式化指令不仅仅局限于%s%d,还有更多的高级用法可以使我们的代码更加灵活、精简。

1. 对齐方式

# 示例代码
print("{:<10d} is less than {:^10d}, and {:>10s} is the biggest.".format(5, 10, "elephant"))

在使用“花括号”格式化方法时,我们可以使用对齐指令来控制输出对齐方式。

  • {:10d} 表示数字向左对齐,占用10个字符,不足时用空格填充;
  • {:10d} 表示数字居中对齐,占用10个字符,不足时用空格填充;
  • {:>10s} 表示字符串向右对齐,占用10个字符,不足时用空格填充。 例如上面的示例,输出结果为:5 is less than 10 , and elephant is the biggest.

2. 格式化符号

# 示例代码
import math
print("The value of pi is approximately %5.2f." % math.pi)
print("The value of pi is approximately {:.2f}.".format(math.pi))

在使用“百分号”格式化方法或者使用“花括号”格式化方法时,我们可以使用格式化符号来进行数值的调整。

  • %5.2f 表示输出一个小数点后两位,总长度为5的浮点数。
  • :.2f 表示输出一个小数点后两位的浮点数,默认长度。 例如上面的示例,输出结果为:The value of pi is approximately 3.14.

3. 多行输出

# 示例代码
print("This is \na multi-line\n output.")
print("""This is 
a multi-line 
output.""")

在使用print format进行多行输出时,我们可以使用双引号、\n或者三个引号来进行换行。 例如上面的示例,输出结果为:

This is 
a multi-line 
output.

或者

This is 
a multi-line 
output.

4. 使用变量名

# 示例代码
print("My name is {name}, and my age is {age}.".format(name="Tom", age=25))

在使用“花括号”格式化方法时,我们可以使用变量名来代替数字。 例如上面的示例,输出结果为:My name is Tom, and my age is 25

5. f-string方法

# 示例代码
name = "Tom"
age = 25
print(f"My name is {name}, and my age is {age}.")

f-string方法是Python 3.6以后的新特性,简化了格式化字符串的语法。 我们只需要在字符串前面加上字母“f”,在变量名后加上花括号{}即可。例如上面的示例,输出结果为:My name is Tom, and my age is 25