0

There can be an input "some word".

I want to replace this input with "<strong>some</strong> <strong>word</strong>" in some other text which contains this input

I am trying with this code:

input = "some word".split()
pattern = re.compile('(%s)' % input, re.IGNORECASE)
result = pattern.sub(r'<strong>\1</strong>',text)

but it is failing and i know why: i am wondering how to pass all elements of list input to compile() so that (%s) can catch each of them.

appreciate any help

3
  • You shouldn't use input as variable name - it's a built-in function... Commented May 14, 2014 at 19:23
  • @Roberto sure, done just for understanding here ;) thanks though Commented May 14, 2014 at 19:24
  • @Roberto that was good point np ;) Commented May 14, 2014 at 19:25

4 Answers 4

2

The right approach, since you're already splitting the list, is to surround each item of the list directly (never using a regex at all):

sterm = "some word".split()
result = " ".join("<strong>%s</strong>" % w for w in sterm)

In case you're wondering, the pattern you were looking for was:

pattern = re.compile('(%s)' % '|'.join(sterm), re.IGNORECASE)

This works on your string because the regular expression would become

(some|word)

which means "matches some or matches word".

However, this is not a good approach as it does not work for all strings. For example, consider cases where one word contains another, such as

a banana and an apple

which becomes:

<strong>a</strong> <strong>banana</strong> <strong>a</strong>nd <strong>a</strong>n <strong>a</strong>pple
Sign up to request clarification or add additional context in comments.

1 Comment

thanks David. very nice didnot know that. how cool is python!
1

It looks like you're wanting to search for multiple words - this word or that word. Which means you need to separate your searches by |, like the script below:

import re

text = "some word many other words"
input = '|'.join('some word'.split())
pattern = re.compile('(%s)' % input, flags=0)
print pattern.sub(r'<strong>\1</strong>',text)

Comments

1

I'm not completely sure if I know what you're asking but if you want to pass all the elements of input in as parameters in the compile function call, you can just use *input instead of input. * will split the list into its elements. As an alternative, could't you just try joining the list with and adding at the beginning and at the end?

Comments

1

Alternatively, you can use the join operator with a list comprehension to create the intended result.

text = "some word many other words".split()
result = ' '.join(['<strong>'+i+'</strong>' for i in text])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.