輸出函式
2024年10月8日大约 3 分鐘
Python 中的 print() 函式是用來將訊息輸出到螢幕的基本方式。這個函式功能強大,支援不同的格式化和輸出控制。
跳脫字符 (Escape Characters)
跳脫字符用來在字串中表示一些特殊的字符或動作,如換行、制表符等。常見的跳脫字符包括:
\n:換行\t:制表符\':單引號\":雙引號\\:反斜線
範例:
print("Hello\nWorld") # 換行輸出
print("Item\tPrice") # 使用制表符對齊
print("He said: \"Hello!\"") # 包含雙引號的字串輸出:
Hello
World
Item Price
He said: "Hello!"格式化輸出
Python 比較常見的格式化輸出方法有 3 種:使用 % 格式符號、使用字串的 format 方法、使用 f-string。
使用 % 進行格式化輸出
在 Python 早期,% 用來進行字串格式化,這種方法依然可用,但現在通常推薦使用 format() 或 f-string。
範例:
name = "John"
age = 25
print("My name is %s and I am %d years old." % (name, age))輸出:
My name is John and I am 25 years old.字串的 format() 方法
Python 字串的 format() 方法允許你根據位置或名稱來格式化輸出。
範例:
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# 指定位置
print("My name is {1} and I am {0} years old.".format(age, name))
# 使用名稱
print("My name is {n} and I am {a} years old.".format(n=name, a=age))輸出:
My name is John and I am 25 years old.
My name is John and I am 25 years old.
My name is John and I am 25 years old.固定長度輸出範例:
name = "John"
print("{:<10}".format(name)) # 左對齊,總長度10
print("{:>10}".format(name)) # 右對齊,總長度10
print("{:^10}".format(name)) # 置中對齊,總長度10輸出:
John
John
Johnformat() 允許在字串中插入變量。這種方法更靈活,可以基於變量的名稱或位置進行操作。
範例:
message = "Hello {name}, you have {count} new messages."
formatted_message = message.format(name="Alice", count=5)
print(formatted_message)輸出:
Hello Alice, you have 5 new messages.使用 f-string 進行格式化輸出
Python 3.6 引入了 f-string,是最簡潔且高效的字串格式化方法。可以直接將變數嵌入字串中,並且支援運算及格式控制。
範例:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# 進行運算
print(f"Next year I will be {age + 1}.")
pi = 3.141592653589793
print(f"I know Pi to three decimal places: {pi:.3f}")輸出:
My name is Alice and I am 30 years old.
Next year I will be 31.
I know Pi to three decimal places: 3.142end 和 sep 參數
end:控制輸出行結束時用什麼字符替代預設的換行符。sep:控制多個參數輸出時之間的分隔符,預設為空格。
範例:
# 改變輸出行結束符
print("Hello", end="!")
print("World")
# 使用不同的分隔符
print("Apple", "Banana", "Cherry", sep=", ")輸出:
Hello!World
Apple, Banana, Cherry練習
- 請撰寫一個程式,使用
print()函式輸出以下內容:
First Line
Indented Line By Tab
"It's a great day!", he said.- 假設你有一個名為
name的變數和一個名為score的變數,分別存放學生的名字和考試成績。請撰寫一個程式,輸出以下格式的字串,並使用.format()方法來填入變數:
"Student Alice has scored 85 points."- 請撰寫一個程式,定義變數
name和age,並使用f-string進行格式化輸出,要求輸出:
"My name is Bob and I am 20 years old. Next year I will be 21."