#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沒有改變的話
就是錯這個地方
“””

#再練習一次

#再練習一次:





![Excel TQC考題208: Competition,自訂格式: [<=50]0; 頁面配置>版面設定 展開>頁首/頁尾 Excel TQC考題208: Competition,自訂格式: [<=50]0; 頁面配置>版面設定 展開>頁首/頁尾](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2022/04/20220411102844_81.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python: pandas.read_excel(r”路徑\檔名.副檔名”, header = None), 自動加上0,1…的欄標籤, DataFrame如何取某一直欄或橫列? 如何用 .iloc[bool_list] 取出判斷式為真的那一列? bool_list = list( df[0] == 0 ) ; bool_list = list(df[0].isin([0])) ; DataFrame如何顯示完整的資料? pandas.set_option ( “display.max_rows”, None) Python: pandas.read_excel(r”路徑\檔名.副檔名”, header = None), 自動加上0,1…的欄標籤, DataFrame如何取某一直欄或橫列? 如何用 .iloc[bool_list] 取出判斷式為真的那一列? bool_list = list( df[0] == 0 ) ; bool_list = list(df[0].isin([0])) ; DataFrame如何顯示完整的資料? pandas.set_option ( “display.max_rows”, None)](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2022/11/20221128164005_44.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言