本文摘至:
为学习记录。
1.引言
Python提供了几种方法来格式化输出,在本篇技术博客中,我们一起来看看Python格式化输出的技术和应用。①首先介绍字符串插值(f-strings)和str.format()
方法来将变量值插入到字符串中,例如print('My name is %s and I am %d years old.' % (name, age));②其次介绍了如何使用格式说明符来控制变量在输出中的显示方式,例如指定浮点数的小数点后位数或整数的进制。例如print('The value of x is {:.2f}'.format(x));③最后演示了如何使用字符串格式化和字符串乘法来创建表格。在实际编程中,我们可以使用格式化输出来打印调试信息、显示统计数据等呀。
2.步骤
2.1 字符串插值
字符串插值是一种最简单的方法,可以在字符串中插入变量。在Python 3.6之前,我们可以使用百分号格式化字符串。在Python 3.6及更高版本中,我们可以使用f字符串(格式化字符串字面量)。
使用百分号格式化字符串的语法如下:
name = '张三'
age = 66
print('My name is %s and I am %d years old.' % (name, age))
输出结果为:
My name is 张三 and I am 66 years old.
使用f字符串格式化字符串的语法如下:
name = '张三'
age = 66
print(f'My name is {name} and I am {age} years old.')
输出结果为:
My name is 张三 and I am 66 years old.
2.2 str.format()方法
str.format()
方法可以将字符串中的占位符替换为变量。使用这种方法时,可以通过位置或名称来指定变量的值。
使用位置指定变量的值的语法如下:
name = '张三'
age = 66
print('My name is {} and I am {} years old.'.format(name, age))
输出结果为:
My name is 张三 and I am 66 years old.
使用名称指定变量的值的语法如下:
name = '张三'
age = 66
print('My name is {n} and I am {a} years old.'.format(n=name, a=age))
输出结果为:
My name is 张三 and I am 66 years old.
2.3 %格式化字符串
%
格式化字符串是一种使用类似于C语言的printf()
函数的语法来格式化字符串的方法。
使用位置指定变量的值的语法如下:
name = '张三'
age = 66
print('My name is %s and I am %d years old.' % (name, age))
输出结果为:
My name is 张三 and I am 66 years old.
使用名称指定变量的值的语法如下:
name = '张三'
age = 66
print('My name is %(n)s and I am %(a)d years old.' % {'n': name, 'a': age})
输出结果为:
My name is 张三 and I am 66 years old.
2.4 format字符串
format()
方法可以使用大括号来替换占位符。大括号中可以包含位置、名称和格式说明符。
使用位置指定变量的值的语法如下:
name = '张三'
age = 66
print('My name is {} and I am {} years old.'.format(name, age))
输出结果为:
My name is 张三 and I am 66 years old.
使用名称指定变量的值的语法如下:
name = '张三'
age = 66
print('My name is {n} and I am {a} years old.'.format(n=name, a=age))
输出结果为:
My name is 张三 and I am 66 years old.
2.5 不同的格式说明符来格式化输出
在这些方法中,可以使用不同的格式说明符来格式化输出。格式说明符用于控制变量在输出中的显示方式,例如指定浮点数的小数点后位数或整数的进制。下面是一些常用的格式说明符:
%d
:整数。%f
:浮点数。%e
:科学计数法。%s
:字符串。%x
:十六进制整数。%o
:八进制整数。
例如,以下代码将会将浮点数保留两位小数输出:
x = 3.141592653589793
print('The value of x is {:.2f}'.format(x))
输出结果为:
The value of x is 3.14
2.6 以表格方式输出
在实际编程中,我们通常需要将数据格式化为表格形式,以便更好地展示和比较数据。下面的示例演示了如何使用str.format()
方法来创建一个简单的表格:
headers = ('Name', 'Age', 'Gender')
data = [('张三', 25, 'Female'),
('Bob', 32, 'Male'),
('Charlie', 18, 'Male')]
# Print headers
print('{:<10} {:<5} {:<10}'.format(*headers))
# Print data
for row in data:
print('{:<10} {:<5} {:<10}'.format(*row))
输出结果为:
Name Age Gender
张三 25 Female
Bob 32 Male
Charlie 18 Male
在上面的示例中,我们使用了字符串格式化和字符串乘法来创建表格。格式字符串'{:<10} {:<5} {:<10}'
包含三个占位符,分别用于显示姓名、年龄和性别。'<10'
表示将字符串左对齐,并在占位符的宽度为10个字符时填充空格。
3. 总结
总之,Python格式化输出是一项非常基础的技术,但在实际编程中非常有用。通过使用字符串插值、str.format()
方法、%
格式化字符串和format()
方法,我们可以将数据格式化为特定的格式,并将其打印到控制台或文件中。在实际编程中,我们可以使用格式化输出来打印调试信息呀。