xxxxxxxxxx
def replace_word_in_string(original_string, target_word, replacement_word):
modified_string = original_string.replace(target_word, replacement_word)
return modified_string
# Example usage
input_string = "The quick brown fox jumps over the lazy dog."
old_word = "fox"
new_word = "cat"
result = replace_word_in_string(input_string, old_word, new_word)
print(result)
xxxxxxxxxx
# How to replace a word in a text file
filename = "sample1.txt"
# SAMPLE1.TXT
# Hello World!
# I am a human.
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('human', 'cat', text)
f.seek(0)
f.write(text)
f.truncate()
# SAMPLE1.TXT
# Hello World!
# I am a cat.
xxxxxxxxxx
# Read in the file
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('ram', 'abcd')
# Write the file out again
with open('file.txt', 'w') as file:
file.write(filedata)
xxxxxxxxxx
#use (variable name).replace('something', 'smth')
#Example:
str = "codegrapper"
str.replace('grapper', 'grepper')
print(str)
#output: codegrepper