0

I know how to replace string in python, but I just want to add some mark around the target string while the target string is caseinsentive. Is there any simple way I can use? For example, I want to add bracket around some words like:

"I have apple."  ->  "I have (apple)."
"I have Apple."  ->  "I have (Apple)."
"I have APPLE."  ->  "I have (APPLE)."
1

1 Answer 1

2

You must make the matching case-insensitive. You can include the flag in the pattern, as in:

import re

variants = ["I have apple.", "I have Apple.", "I have APPLE and aPpLe."]

def replace_apple_insensitive(s):
    # Adding (?i) makes the matching case-insensitive
    return re.sub(r'(?i)(apple)', r'(\1)', s)

for s in variants:
    print(s, '-->', replace_apple_insensitive(s))

# I have apple. --> I have (apple).
# I have Apple. --> I have (Apple).
# I have APPLE and aPpLe. --> I have (APPLE) and (aPpLe).

Or you can compile the regex and keep the case-insensitive flag out of the pattern:

apple_regex = re.compile(r'(apple)', flags=re.IGNORECASE) # or re.I
print(apple_regex.sub(r'(\1)', variants[2]))

#I have (APPLE) and (aPpLe).
Sign up to request clarification or add additional context in comments.

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.