type
status
date
Jun 21, 2023 09:37 AM
slug
summary
tags
category
icon
password
print() 内建函数用于打印输出,默认打印到标准输出 sys.stdout。
2.1. 直接打印输出 ¶
print() 内建函数用于打印输出,默认打印到标准输出 sys.stdout。
ㅤ | print("Hello %s: %d" % ("World", 100))
print("end")
>>>
Hello World: 100
end |
print() 函数会自动在输出行后添加换行符。
2.2. 不换行打印输出 ¶
ㅤ | strs = "123"
for i in strs:
print(i),
print("end")
>>>
1 2 3 end |
通过在 print() 语句后添加”,” 可以不换行,但会自动在输出后添加一个空格。
print() 函数支持 end 参数,默认为换行符,如果句尾有逗号,则默认为空格,可以指定 end 参数为空字符,来避免输出空格
ㅤ | str0 = "123"
print(str0, end='')
print("end")
>>>
123end |
使用 sys.stdout 模块中的 write() 函数可以实现直接输出。
ㅤ | import sys
strs = "123"
for i in strs:
sys.stdout.write(i)
print("end")
>>>
123end |
2.3. 分隔符打印多个字符串 ¶
print() 函数支持一次输入多个打印字符串,默认以空格分割,可以通过 sep 参数指定分割符号。
2.4. 格式化输出到变量 ¶
ㅤ | tmpstr = ("Number is: %d" % 100)
print(tmpstr)
hexlist = [("%02x" % ord(x) )for x in tmpstr]
print(' '.join(hexlist))
print("end")
>>>
Number is: 100
4e 75 6d 62 65 72 20 69 73 3a 20 31 30 30
end |
通过打印字符串的 ascii 码,可以看到换行符是 print() 函数在打印时追加的,而并没有格式化到变量中。
2.5. 长行打印输出 ¶
ㅤ | def print_long_line():
print("The door bursts open. A MAN and WOMAN enter, drunk and giggling,\
horny as hell.No sooner is the door shut than they're all over each other,\
ripping at clothes,pawing at flesh, mouths locked together.")
print_long_line()
>>>
The door bursts open. A MAN and WOMAN enter, drunk and giggling,horny as
hell.No sooner is the door shut than they're all over each other, ripping
at clothes,pawing at flesh, mouths locked together. |
如果 print() 函数要打印很长的数据,则可使用右斜杠将一行的语句分为多行进行编辑,编译器在执行时, 将它们作为一行解释,注意右斜杠后不可有空格,且其后的行必须顶格,否则头部空格将被打印。
ㅤ | def print_long_line():
print("""The door bursts open. A MAN and WOMAN enter, drunk and giggling,
horny as hell.No sooner is the door shut than they're all over each other,
ripping at clothes,pawing at flesh, mouths locked together.""") |
使用一对三引号和上述代码是等价的,以上写法每行字符必须顶格,否则对齐空格将作为字符串内容被打印,这影响了代码的美观。可以为每行添加引号来解决这个问题。
ㅤ | def print_long_line():
print("The door bursts open. A MAN and WOMAN enter, drunk and giggling,"
"horny as hell.No sooner is the door shut than they're all over each other,"
"ripping at clothes,pawing at flesh, mouths locked together.")
print_long_line()
>>>
The door bursts open. A MAN and WOMAN enter, drunk and giggling,horny as
hell.No sooner is the door shut than they're all over each other, ripping
at clothes,pawing at flesh, mouths locked together. |
2.6. 打印含有引号的字符串 ¶
Python 使用单引号或者双引号来表示字符,那么当打印含有单双引号的行时如何处理呢?
ㅤ | print("It's a dog!")
print('It is a "Gentleman" dog!')
print('''It's a "Gentleman" dog!''')
>>>
It's a dog!
It is a "Gentleman" dog!
It's a "Gentleman" dog! |
2.7. 打印输出到文件 ¶
print(value, …, sep=’ ‘, end=’n’, file=sys.stdout, flush=False)
print() 函数支持 file 参数来指定输出文件的描述符。默认值是标准输出 sys.stdout,与此对应, 标准的错误输出是 sys.stderr,当然也可以指定普通文件描述符。
输出到磁盘文件时,为了保证实时性,根据实际情况可能需要把 flush 参数设置为 True。
ㅤ | logf = open("logfile.log", "a+")
print("123", file=logf, flush=True) |
2.8. 对齐输出(左中右对齐)¶
通过 print() 函数可以直接实现左对齐输出。print() 函数不能动态指定对齐的字符数, 也不能指定其他填充字符,只能使用默认的空格进行填充。
ㅤ | man = [["Name", "John"], ["Age", "25"], ["Address", "BeiJing China"]]
for i in man:
print("%-10s: %s" % (i[0], i[1]))
>>>
Name : John
Age : 25
Address : BeiJing China |
Python 中字符串处理函数 ljust(), rjust() 和 center() 提供了更强大的对齐输出功能。
左对齐 ljust() 示例,计算特征量的长度,决定动态偏移的字符数。
ㅤ | len_list=[len(x[0]) for x in man]
offset = max(len_list) + 5 # 增加5个空白符号
for i in man:
print("%s: %s" % (i[0].ljust(offset), i[1]))
>>>
Name : John
Age : 25
Address : BeiJing China |
左对齐 rjust() 示例:
ㅤ | len_list=[len(x[0]) for x in man]
offset = max(len_list) + 5 # 增加5个空白符号
for i in man:
print("%s: %s" % (i[0].ljust(offset), i[1]))
>>>
Name : John
Age : 25
Address : BeiJing China |
居中对齐示例,这里以字符‘~’填充。
ㅤ | lines = ["GNU GENERAL PUBLIC LICENSE", "Version 3, 29 June 2007"]
len_list=[len(x) for x in lines]
center_num = max(len_list) + 30
for i in lines:
print(i.center(center_num, "~"))
>>>
~~~~~~~~~~~~~~~GNU GENERAL PUBLIC LICENSE~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~Version 3, 29 June 2007~~~~~~~~~~~~~~~~~ |
2.9. 格式化输出 ¶
更多格式化输出请参考 字符串格式化 。
2.9.1. 百分号格式化 ¶
与 C 语言类似,python 支持百分号格式化,并且基本保持了一致。
2.9.1.1. 数值格式化 ¶
整数格式化符号可以指定不同进制:
- %o —— oct 八进制
- %d —— dec 十进制
- %x —— hex 十六进制
- %X —— hex 十六进制大写
ㅤ | print('%o %d %x %X' % (10, 10, 10, 10))
>>>
12 10 a A |
浮点数可以指定保留的小数位数或使用科学计数法:
- %f —— 保留小数点后面 6 位有效数字,%.2f,保留 2 位小数位。
- %e —— 保留小数点后面 6 位有效数字,指数形式输出,%.2e,保留 2 位小数位,使用科学计数法。
2.9.1.2. 字符串格式化 ¶
- %s —— 格式化字符串
- %10s —— 右对齐,空格占位符 10 位
- %-10s —— 左对齐,空格占位符 10 位
- %.2s —— 截取 2 个字符串
- %10.2s —— 10 位占位符,截取两个字符
2.9.2. format 格式化 ¶
format() 是字符串对象的内置函数,它提供了比百分号格式化更强大的功能,例如调整参数顺序,支持字典关键字等。它该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号 ‘{}’ 作为特殊字符代替 ‘%’。
2.9.2.1. 位置匹配 ¶
位置匹配有以下几种方式:
- 不带编号,即 “{}”,此时按顺序匹配
- 带数字编号,可调换顺序,即 “{1}”、“{2}”,按编号匹配
- 带关键字,即 “{name}”、“{name1}”,按字典键匹配
- 通过对象属性匹配,例如 obj.x
- 通过下标索引匹配,例如 a[0],a[1]
通过对象属性匹配,可以方便地实现对象的 str 方法:
ㅤ | class Point:
def __init__(self, x, y):
self.x, self.y = x, y
# 通过对象属性匹配
def __str__(self):
return 'Point({self.x}, {self.y})'.format(self=self)
>>>str(Point(5, 6))
'Point(4, 2)' |
对于元组,列表,字典等支持索引的对象,支持使用索引匹配位置:
ㅤ | >>> point = (0, 1)
>>> 'X: {0[0]}; Y: {0[1]}'.format(point)
'X: 0; Y: 1'
>>> a = {'a': 'val_a', 'b': 'val_b'}
# 注意这里的数字 0 代表引用的是 format 中的第一个对象
>>> b = a
>>> 'X: {0[a]}; Y: {1[b]}'.format(a, b)
'X: val_a; Y: val_b' |
2.9.2.2. 数值格式转换 ¶
- ‘b’ - 二进制。将数字以 2 为基数进行输出。
- ‘c’ - 字符。在打印之前将整数转换成对应的 Unicode 字符串。
- ‘d’ - 十进制整数。将数字以 10 为基数进行输出。
- ‘o’ - 八进制。将数字以 8 为基数进行输出。
- ‘x’ - 十六进制。将数字以 16 为基数进行输出,9 以上的位数用小写字母。
- ‘e’ - 幂符号。用科学计数法打印数字。用’e’表示幂。
- ‘g’ - 一般格式。将数值以 fixed-point 格式输出。当数值特别大的时候,用幂形式打印。
- ‘n’ - 数字。当值为整数时和’d’相同,值为浮点数时和’g’相同。不同的是它会根据区域设置插入数字分隔符。
- ‘%’ - 百分数。将数值乘以 100 然后以 fixed-point(‘f’) 格式打印,值后面会有一个百分号。
各种进制转换:
ㅤ | >>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
# 在前面加“#”,自动添加进制前缀
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010' |
2.9.2.3. 位数对齐和补全 ¶
- <(默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐
- 取字符数或者位数 “{:4s}”、”{:.2f}” 等
2.9.2.4. 正负号和百分显示 ¶
正负符号显示通过 %+f, %-f, 和 % f 实现:
ㅤ | >>> '{:+f}; {:+f}'.format(3.14, -3.14) # 总是显示符号
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # 若是+数,则在前面留空格
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # -数时显示-,与'{:f}; {:f}'一致
'3.140000; -3.140000' |
打印百分号,注意会自动计算百分数:
ㅤ | >>> 'Correct answers: {:.2%}'.format(1/2.1)
'Correct answers: 47.62%'
# 以上代码等价于
>>> 'Correct answers: {:.2f}%'.format(1/2.1 * 100) |
2.9.2.5. 千位分割数字 ¶
用 “,” 分隔数字,每一千进位:
ㅤ | >>> '{:,}'.format(1234567890)
'1,234,567,890' |
2.9.2.6. 时间格式化 ¶
ㅤ | >>> import datetime
>>> d = datetime.datetime(2018, 5, 4, 11, 15, 38)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2018-05-04 11:15:38' |
2.9.2.7. 占位符嵌套 ¶
2.9.2.8. repr 和 str 占位符 ¶
ㅤ | """
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
conversion ::= "r" | "s" | "a"
这里只有三个转换符号,用"!"开头。
"!r"对应 repr();"!s"对应 str(); "!a"对应ascii()。
"""
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2" # 输出结果是一个带引号,一个不带 |
2.9.2.9. format 缩写形式 ¶
可在格式化字符串前加 f 以达到格式化的目的,在 {} 里加入对象,这是 format 的缩写形式:
本文由简悦 SimpRead 转码