TQC+ 程式語言Python 906 字串資料取代
題目說明:
請撰寫一程式,要求使用者輸入檔名data.txt、字串s1和字串s2。程式將檔案中的字串s1以s2取代之。
範例輸入
data.txt
pen
sneakers
範例輸出
=== Before the replacement
watch shoes skirt
pen trunks pants
=== After the replacement
watch shoes skirt
sneakers trunks pants
檔案下載:
data.txt
程式碼:
f_name = input()
str_old = input()
str_new = input()
file = open(f_name, 'r+')
datas = file.read()
print("=== Before the replacement")
print(datas)
print("=== After the replacement")
datas = datas.replace(str_old, str_new)
print(datas)
file.seek(0)
file.write(datas)
file.close()