0

I'm using python 3 and I just want to use only an efficient and effective single line of code for the following problem.

Suppose, I have a word and it has multiple combinations. I want to replace all the combinations with an efficient single line of code. For example,

s2 = 'Hello Donald. DONALD is playing with his son. His son loves to play with donald' 
s2.replace('Donald', 'John')

This replaces only Donald not DONALD and donald.

How can I replace all combinations ( Donald, DONALD, donald ) of Donald by John.

More explicitly :

s3 = 'NO No nO no' 

I can use

s3.replace('NO', 'yes').replace('No', 'yes').replace('nO', 'yes').replace('no', 'yes')

But, the more combinations, the more replace functions. How can I use replace function effectively and efficiently to replace all combinations NO by yes.

4 Answers 4

4
import re
re.sub("(?i)no","yes", "no No nO NO") # yes yes yes yes
Sign up to request clarification or add additional context in comments.

Comments

2

You can use regular expressions and in particular re.sub in case-insensitive mode:

import re

re.sub('donald', 'john', 'DoNalD duck', flags=re.I)
# john duck

Comments

1

data_str = "No NO nO no".upper().replace('NO', 'YES')

print(data_str)

1 Comment

Thank you @krishna
0

If you also want to eliminate possible accents ÁÀÃÂÇÉÊÍÕÓÔÚáàãâçéêíõóôú you can first 'normalize' the char as in this regex-free code golf example When I grow up I want to be ASCII.

Then proceed to make all chars 'upper' or 'lower' and replace the desired string element.

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.