Can the Python .replace() function replace whole phrases?

Question:

I’m a video editor trying to automate word docs of talent scripts into STR files for captions to speed up the process. Since each video is structured the same, the idea works pretty well. In the scripts, there are editing directions that I’m trying to remove from the STR file I’m creating with Python and the python-docx library by using the .replace() function, however this doesn’t seem to be working. These all begin with ‘(CUT’ and the following possible sentences vary. The program correctly picks up where these sentences are occurring but the replace function yields no resulting change. What am I doing wrong here?

for x in range(2,len(doc.paragraphs)):
newPara = doc.paragraphs[x].text

if (newPara.find('(CUT') != -1):
    newPara.replace('(CUT', '')
   
    if (newPara.find('COMPLETE)') != -1):
        newPara.replace(' AWAY COMPLETE)', '')
       
    elif (newPara.find('TITLE)') != -1):
        newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara.replace(' BACK TO SIDE)', '')
Asked By: sunnydorange

||

Answers:

str.replace() doesn’t mutate the original string – it returns the mutated string.
you should re-assign to you variable:

#...
if (newPara.find('(CUT') != -1):
    newPara = newPara.replace('(CUT', '')

    if (newPara.find('COMPLETE)') != -1):
        newPara = newPara.replace(' AWAY COMPLETE)', '')

    elif (newPara.find('TITLE)') != -1):
        newPara = newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara = newPara.replace(' BACK TO SIDE)', '')
Answered By: A. Rom

As the guy above said, strings are immutable and the str.replace() function returns a new string.

But adding to your code.

You don’t need all those conditionals, the if the str.replace() does not find the substring you’re looking for it returns the same string.

Example:

newPara = '(CUT AWAY COMPLETE) AWAY TO TITLE) BACK TO SIDE)Empty String'

if (newPara.find('(CUT') != -1):
    newPara = newPara.replace('(CUT', '')
    newPara = newPara.replace(' AWAY COMPLETE)', '')
    newPara = newPara.replace(' AWAY TO TITLE)', '')
    newPara = newPara.replace(' BACK TO SIDE)', '')

print(newPara)

prints: ‘Empty String’

also:

if (newPara.find('(CUT') != -1):
    for substring in ['(CUT',' AWAY COMPLETE)',' AWAY TO TITLE)', ' BACK TO SIDE)']:
        newPara = newPara.replace(substring, '')
Answered By: John
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.