#Python TQC考題906 字串資料取代
“””
以下為視訊教學
最後一行錯了!
正確應為:
file.write(data.replace(s1,s2))
“””

“””
read.txt內容:
watch shoes skirt
pen trunks pants
“””
fname=input()
strold=input()
strnew=input()
with open(fname,”r+“,encoding=”utf-8”) as file:
# fname是input()進來,不需要” ” , r+可讀寫
#若將r+改成w+,replace前後都是空的
data=file.read()
print(“=== Before the replacement”)
print(data)
print(“=== After the replacement”)
print(data.replace(strold,strnew))
file.seek(0) #回到檔案起點
#少這一行的話,位置於文件之末,
# 會於文件末再多一段資料
#而非蓋掉原資料
file.write(data)
“””
這一行應該是錯的,
data.txt將不會被新資料寫入
應該修正為:
file.write(data.replace(strold,strnew))
這樣才把新資料寫入data.txt
“””

“””
datanew = data.replace(strold,strnew)
print(datanew)
要用datanew承接data.replace(strold,strnew)
再印datanew
印data的話,仍是舊資料
以下有成功將sneakers寫入data.txt,
注意: f.write(datanew) ,
不是f.write(data)
刪除錯好幾次的程式碼
data.txt沒有改變的話
就是錯這個地方
“””

#再練習一次

#再練習一次:


![Python: list.index() 只能找到第一個元素的index,若元素有重複,如何找出所有index? indexes = [index for index, value in enumerate(my_list) if value == target] Python: list.index() 只能找到第一個元素的index,若元素有重複,如何找出所有index? indexes = [index for index, value in enumerate(my_list) if value == target]](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2024/10/20241010101216_0_12b6c0.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![Python: 如何用numpy.ndarray的reshape 將3D array轉為2D array,再轉為pandas.DataFrame? arr.reshape( arr.shape[0] * arr.shape[1] , -1) Python: 如何用numpy.ndarray的reshape 將3D array轉為2D array,再轉為pandas.DataFrame? arr.reshape( arr.shape[0] * arr.shape[1] , -1)](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230320082325_85.png?quality=90&zoom=2&ssl=1&resize=350%2C233)




![Python: matplotlib繪圖,如何限定座標軸範圍? plt.axis([xmin, xmax, ymin, ymax]) Python: matplotlib繪圖,如何限定座標軸範圍? plt.axis([xmin, xmax, ymin, ymax])](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2023/02/20230208101745_93.jpg?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言