我有一个包含以下行的文本文件 - a boy is drinking water
。我称之为文件A.txt
我的目标是用用户在A.txt中输入的任何内容替换单词water
。
并保留其他东西完好无损。
如果A.txt更改为a boy is drinking juice
并将A.txt作为参数传递给Python脚本,我希望输出为a boy is drinking juice
。
我们如何只替换字符串中的特定字母。
答案 0 :(得分:4)
打开文件,检索内容
要替换单词中的某个字符串,请使用textFromFile.replace('oldtext','newtext')
将内容保存到文件。
答案 1 :(得分:-1)
使用此代码
namespace string_replace
{
class Program
{
static void Main(string[] args)
{
string text = System.IO.File.ReadAllText(@"a.txt");
//read the text to replace
text.Replace("water","user_string");
System.IO.File.WriteAllText(@"A.txt", text);
}
}
}