0

I'm trying to find a word in a simple string no matter how it's written. For example:

'Lorem ipsum dolor sit amet lorem.'

Let's say I search for 'lorem' written in lowercase and I'd like to replace both 'lorem' and 'Lorem' with 'example'. The thing is, I want to search and replace the word no matter how it's written.

I think this should be done using regex but I'm not very familiar with it. Maybe you guys can help.

Ovidiu G
  • 1,253
  • 5
  • 25
  • 47

4 Answers4

1
import re
sentence = "Lorem ipsum dolor sit amet lorem."
search_key = "Lorem"
print(re.sub(r'%s' % search_key.lower(), 'example', sentence.lower()))
>>> example ipsum dolor sit amet example.
Veera Balla Deva
  • 790
  • 6
  • 19
0

You just need to make the letters upper or lower case. I made lower case for this time.

import re

x='Lorem ipsum dolor sit amet lorem.'.lower()
y=input(" What word do you want to chage?").lower()


if not y in x:
    print("This word is not in the sentence. You cannot change it!")
else:
    z= y + " which word you want to write instead?"
    z=input(z)
    t=re.sub(y,z,x)
    print(t)
Land Owner
  • 182
  • 11
0

Below code should work for you.

import re
pattern_rep = re.compile(re.escape('lorem'), re.IGNORECASE)
new_pattern=pattern_rep.sub('example', 'Lorem ipsum dolor sit amet lorem')
print(new_pattern)
0

Another way without regex (works for your example in the question):

s = 'Lorem ipsum dolor sit amet lorem.'
print(s.replace('lorem', 'example').replace('Lorem', 'example'))
# example ipsum dolor sit amet example.
Austin
  • 25,759
  • 4
  • 25
  • 48