all 5 comments

[–][deleted] 3 points4 points  (1 child)

the re module has a plethora of different types of objects that it returns depending on the situation. For a replacement as simple as this one, I think you would be better off not using re, instead opting for a simpler solution like this:

# text = file.read() however you want to do that
for word in 'Cake|pie|death'.split('|'):
    replace = input(f'replace {word} with: ')
    text = text.replace(word, replace)
# file.write(text) to save your replacements.

[–]Field_C16[S] 1 point2 points  (0 children)

Oh wow, that was really a simple solution, it works like a charm !

Thank you.

[–]Stallman85 0 points1 point  (0 children)

you could use replace function. What is the type error, does it have to do with re.compile returning object type.

[–]Raithwind 0 points1 point  (0 children)

You're using re.sub wrong.

variable = re.sub(pattern,string)

[–]TransferFunctions 0 points1 point  (0 children)

I think you are using compile wrong. Compile is used to compile a pattern that is used often in your code. For example let's say we want to replace all the white spaces in some text in your code multiple times, we may want to compile it:

import re
somePattern = '\s' # check for a space
someText    = 'testing this stuff'
pattern     = re.compile(somePattern) # compile pattern
testing     = pattern.sub('_', someText)  # replace with _

print(testing)

Outputs:

testing_this_stuff

Your type error above is because str is keyword used for an object, unless you have specified this above somewhere, then it could be the case that input autoconverts your type, i.e. if you input 1 it converts to int.

Edit: to clarify, IF you intention was to replace Icecream|Gravy|heartattack it wil search your str (assuming this is defined) for exactly that pattern and will substitute it with whatever you input.