1. 程式人生 > 其它 >Python程式設計 從入門到實踐 練習10-1、練習10-2

Python程式設計 從入門到實踐 練習10-1、練習10-2

技術標籤:python程式設計從入門到實踐python

10-1 Python學習筆記

filename = 'learning_python.txt'

# 第一次列印讀取整個檔案
with open(filename) as file_object:
	contents = file_object.read()
	print(contents)

# 第二次列印時遍歷檔案物件
with open(filename) as file_object:
	for line in file_object:
		print(line.rstrip())

# 第三次列印時將各行儲存在一個列表中,再在with程式碼塊外列印它們
with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())

10-1輸出

10-2 C語言學習筆記

filename = 'learning_python.txt'

with open(filename) as file_object:
	message = file_object.read()

print(message.replace('Python', 'C'))

10-2輸出
注意單獨呼叫方法replace不會改變message本身的值,所以如果採用下述寫法message的輸出並不會變。

---snip---
message.replce('Python', 'C')
print(message)

使用方法replace重新賦值,則輸出改變。

message = message.replace('Python', 'C')
print(message)