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
s = 'Some String test'
print(s.replace(' ', '-'))
# Output
# Some-String-test
xxxxxxxxxx
#user replace
string = "Hello, World!"
string = string.replace("World", "Universe")
print(string) #prints Hello, Universe!
xxxxxxxxxx
# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A
text = "python is too difficult , I have a good experience with it"
#python is too difficult I am using this text for example only
print(text.replace('difficult', 'easy'))
#####output#####
#python is too easy , I have a good experience with it
xxxxxxxxxx
# Syntax - str.replace(old, new [, count])
song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string is unchanged
print('Original string:', song)
print('Replaced string:', replaced_song)
song = 'let it be, let it be, let it be'
# maximum of 0 substring is replaced
# returns copy of the original string
print(song.replace('let', 'so', 0))
xxxxxxxxxx
#use (variable name).replace('something', 'smth')
#Example:
str = "codegrapper"
str.replace('grapper', 'grepper')
print(str)
#output: codegrepper