Python 入門到精通 — 輸出
內容
Python 的格式化輸出 ✈️
Python 有多種顯示程序輸出和輸入的方法,例如在計算機屏幕上打印或寫入文件或從鍵盤輸入命令。
範例
num = 123
name = 'John'
print(num)
print(name)
結果
123
John
格式化輸出詳解
Python 有三種方式 ... 1. f-strings。 2. str.format() 方式 or 手動格式化。 3. % operator ( 舊的用法輸出格式化 )。
範例 @ f-strings
"""
f-strings
"""
import math
pi = math.pi
print(type(pi))
print(f"PI = {pi:.3f}")
print(f'PI = {pi:.10f}')
print('PI = {pi:.10f}')
# '!a' applies asciiO,
# '!s' applies strO, and
# '!r' applies reprO
animals = 'cat'
print(type(animals))
print(f'My {animals}.')
print(f'My {animals!r}.')
print(f'My {animals!s}.')
print(f'My {animals!a}.')
name = {'John': 18, 'Jack': 20, 'Tony': 25}
print(type(name))
print('12345 ==> 12345')
for name, age in name.items():
# The integer after ':' can set the width
# of the field characters
print(f'{name:5} ==> {age:5d}')
結果
<class 'float'>
PI = 3.142
PI = 3.1415926536
PI = {pi:.10f}
<class 'str'>
My cat.
My 'cat'.
My cat.
My 'cat'.
<class 'dict'>
12345 ==> 12345
John ==> 18
Jack ==> 20
Tony ==> 25
範例 @ str.format()
"""
str_format
"""
print("My {}'s name is {}!".format("cat", "Salud"))
print('{0} and {0}'.format('John', 'Jack'))
print('{0} and {1}'.format('John', 'Jack'))
print('{1} and {0}'.format('John', 'Jack'))
print('{1} and {1}'.format('John', 'Jack'))
print("The {cat}'s name is {name}."
.format(cat='cat', name='Salud'))
print('The cat of {0}, {1}, and {other}.'
.format('John', 'Jack', other='Tony'))
table = {'John': 12, 'Jack': 20, 'Tony': 30}
print('Jack: {0[Jack]:d}; Tony: {0[Tony]:d}; '
'John: {0[John]:d}'.format(table))
table = {'John': 12, 'Jack': 20, 'Tony': 30}
print('Tony: {Tony:d}; John: {John:d}; Jack: {Jack:d}'
.format(**table))
print('0123456789A')
for x in range(1, 5):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
結果
My cat's name is Salud!
John and John
John and Jack
Jack and John
Jack and Jack
The cat's name is Salud.
The cat of John, Jack, and Tony.
Jack: 20; Tony: 30; John: 12
Tony: 30; John: 12; Jack: 20
0123456789A
1 1 1
2 4 8
3 9 27
4 16 64
範例 @ 手動格式化
"""
manual_string_formatting
"""
print('0123456789A')
for x in range(1, 5):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
# Note use of 'end' on previous line
print(repr(x*x*x).rjust(4))
print('1'.zfill(3))
print('1'.zfill(5))
print('1'.zfill(7))
print('-1'.zfill(7))
print('1.0'.zfill(5))
print('1.11'.zfill(5))
print('1.111'.zfill(5))
結果
0123456789A
1 1 1
2 4 8
3 9 27
4 16 64
001
00001
0000001
-000001
001.0
01.11
1.111
範例 @ % operator ( old string formatting )
"""
old_string_formatting
"""
_id_ = 123
name = 'Tony'
age = 35
high = 175.5
weight = 65.3
# %s
print('My name is %s' % name)
# %d
print('My _id_ is %d' % _id_)
print('My age is %d' % age)
# %f
print('My high is %.3f' % high)
print('My weight is %.1f' % weight)
# 000123
print('My _id_ is %06d' % _id_)
# 123
print('My _id_ is %03d' % _id_)
# 123
print('My _id_ is %02d' % _id_)
# %s %d
print('My name is %s and I am %d years old.'
% (name, age))
print('My name is %s and I am %d years old.'
% (name, age+1))
# %d %s %f
print('ID : %d | Name : %s | Age : %d | High : '
'%.2f | Weight : %.2f'
% (_id_, name, age, high, weight))
# %s %s %s
print('ID : %s | Name : %s | Age : %s | High : '
'%s | Weight : %s'
% (_id_, name, age, high, weight))
結果
My name is Tony
My _id_ is 123
My age is 35
My high is 175.500
My weight is 65.3
My _id_ is 000123
My _id_ is 123
My _id_ is 123
My name is Tony and I am 35 years old.
My name is Tony and I am 36 years old.
ID : 123 | Name : Tony | Age : 35 | High : 175.50 | Weight : 65.30
ID : 123 | Name : Tony | Age : 35 | High : 175.5 | Weight : 65.3
其它常用的字元
\\ : 反斜杠(\) \' : 單引號(') \" : 雙引號(") \n : ASCII 换行符(LF) \r : ASCII 回车符(CR) \t : ASCII 水平制表符(TAB)
範例
"""
other_common_conversion_characters
"""
# '\n', like C language
print("Hello")
print("Hello\n")
print("Hello\r")
print("Hello\n\r")
print("Hello\'s")
print("Hello\\")
print("\"Hello\"")
print("Hello\t", end='')
print("Hello")
print("-----------------")
# When end=' ' is omitted, print() will default to end='\n'
# print("Hello") = print("Hello", end='\n')
print("Hello", end='\n')
print("Hello")
print("Hello", end='\t')
print("Hello")
print("-----------------", end='\r')
結果
Hello
Hello
Hello
Hello
Hello's
Hello\
"Hello"
Hello Hello
-----------------
Hello
Hello
Hello Hello
-----------------
Process finished with exit code 0