Simple replace all
Replacing all occurrences of a string with another one.
str = "Python2 is cool and Python2 is chill"
str = str.replace("Python2", "Python3")
print (str)
result:
Python3 is cool and Python3 is chill
Have in mind that replace is case sensitive. Replace python2 will do nothing while Python2 will work!
Python string replace first only
If you want to replace first N items from string you can use replace with 3 parameters. The last one is border which define when the replace should stop:
str = "Python2 is cool and Python2 is chill and Python2 is funny"
str = str.replace("Python2", "Python3", 1)
print (str)
str = str.replace("Python2", "Python3", 2)
print (str)
result:
Python3 is cool and Python2 is chill and Python2 is funny
Python3 is cool and Python3 is chill and Python2 is funny
Python string replace only digits
Replacing digits can be done very easy by using regex:
import re
str = 'The date was - 2011-01-18 00:00:00.0 and the time was 22:11'
strnew = re.sub('\w*[0-9]\w*', '', str)
print (strnew)
result:
The date was - -- ::. and the time was :
Python string replace multiple characters
Replacing multiple characters can be simulated by. First one will replace all occurrences one by one. The advantage is that you can customize it. The second one is my favorite and it's easy for reading:
strnew = 'The date was - -- ::. and the time was :'
print (strnew.replace('-', '').replace(':', '').replace('.', ''))
for ch in [':','-', ',', '.']:
if ch in strnew:
strnew=strnew.replace(ch,'')
print(strnew)
result:
The date was and the time was
The date was and the time was
Python string replace in file names
The code below is iterating all files in a folder /home/user/test/ . Check if the file name contains the bad word Java (case sensitive ). And if the file has it in the name then replace the first 2 occurences with empty string and rename the files.
#!/usr/bin/env python
from os import rename, listdir
bad = "Java"
dir = '/home/user/test/'
fnames = listdir(dir)
for fname in fnames:
print(fname)
if fname.startswith(bad):
newname = dir + fname.replace(bad, '', 2)
rename(dir + fname, newname)
fnames = listdir(dir)
for fname in fnames:
print(fname)
result:
#before
JavaIsGoodJava.txt
JavaIsBadJava.txt
JavaIsBadJavaJava.txt
#after
IsBad.txt
IsBadJava.txt
IsGood.txt