文章目錄
- 1. 輸入與 `input()`
- 示例:
- 提示:
- 2. 輸出與 `print()`
- 基本用法:
- 格式化輸出:
- 使用 f-string(推薦):
- 使用 `str.format()`:
- 使用占位符:
- `print()` 的關鍵參數:
- 3. 文件輸入與輸出
- 打開文件:
- 讀取文件:
- 常用讀取方法:
- 寫入文件:
- 文件迭代:
- 提示:
- 4. 字符編碼處理
- 示例:
- 5. 進階:格式化字符串與 `repr()`
- 6. 總結
在 Python 3 中,輸入與輸出是程序與外界交互的重要方式。無論是讀取用戶輸入、打印結果,還是處理文件,Python 3 提供了一組強大且直觀的工具。本篇博客將優雅地總結 Python 3 的輸入與輸出方法,幫助您更好地理解和應用。
1. 輸入與 input()
在 Python 3 中,input()
函數用于從用戶獲取輸入。與 Python 2 中的 raw_input()
不同,input()
會將用戶輸入的內容作為字符串返回。
示例:
name = input("請輸入你的名字: ")
print(f"你好, {name}!")
提示:
- 如果需要特定類型的輸入,例如整數或浮點數,可以結合
int()
或float()
進行類型轉換:age = int(input("請輸入你的年齡: ")) print(f"明年你將是 {age + 1} 歲。")
2. 輸出與 print()
print()
是 Python 的核心輸出函數,用于在控制臺顯示信息。它功能強大且靈活。
基本用法:
print("Hello, World!")
格式化輸出:
Python 3 支持多種格式化字符串的方式。
使用 f-string(推薦):
name = "Alice"
age = 25
print(f"{name} 的年齡是 {age}。")
使用 str.format()
:
print("{} 的年齡是 {}。".format("Alice", 25))
使用占位符:
print("%s 的年齡是 %d。" % ("Alice", 25))
print()
的關鍵參數:
-
sep
: 指定多個值之間的分隔符。print("Python", "is", "awesome", sep="-") # 輸出: Python-is-awesome
-
end
: 指定輸出的結尾字符,默認是換行符。print("Hello", end=" ") print("World!") # 輸出: Hello World!
-
file
: 指定輸出目標,例如文件對象。with open("output.txt", "w") as f:print("Hello, File!", file=f)
3. 文件輸入與輸出
Python 3 提供了強大的文件讀寫能力,通過內置的 open()
函數可以輕松實現。
打開文件:
open()
函數的基本語法如下:
file = open(filename, mode, encoding=None)
filename
: 文件路徑。mode
: 文件操作模式,例如:"r"
: 只讀(默認)。"w"
: 寫入,覆蓋文件內容。"a"
: 追加。"b"
: 二進制模式(如"rb"
)。
encoding
: 文本文件的編碼方式(如"utf-8"
)。
讀取文件:
with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print(content)
常用讀取方法:
read(size)
:讀取指定字節數。readline()
:逐行讀取。readlines()
:讀取所有行并返回一個列表。
寫入文件:
with open("example.txt", "w", encoding="utf-8") as file:file.write("Hello, World!\n")
文件迭代:
with open("example.txt", "r", encoding="utf-8") as file:for line in file:print(line.strip())
提示:
始終使用 with
語句處理文件,確保文件在使用后正確關閉。
4. 字符編碼處理
Python 3 默認使用 utf-8
編碼。無論是輸入還是輸出,都建議明確指定編碼,尤其是在處理多語言文本時。
示例:
with open("example.txt", "w", encoding="utf-8") as file:file.write("你好,世界!")with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print(content)
5. 進階:格式化字符串與 repr()
當需要調試或顯示對象的精確表示時,可以使用 repr()
:
value = 42
print(repr(value)) # 輸出: 42
結合 repr()
和格式化字符串:
print(f"The result is {value!r}")
6. 總結
Python 3 的輸入與輸出功能設計直觀且靈活,涵蓋了從控制臺交互到文件處理的多種場景。通過熟練掌握這些工具,您可以輕松構建功能豐富、用戶友好的 Python 程序。