Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to input a variable as the pattern in re.sub while using ^

I am trying to use the re.sub to replace every character in a string, (word), with ‘ _ ‘ except for my variable character , (answer), and I am having trouble getting re.sub to properly read (answer), which is in string form, while using ^. I am able to get it to read (answer) properly when I am not using ^. I’ve tried using .format() but this also doesn’t seem to work for me. When I run it in it’s current state it replacces all the characters in the string with ‘ _ ‘ instead of just the non-answer characters. (Note: I am extremely new to python so I apologize for any bad code)

known_word = (re.sub('[^{}]'.format(answer), ' _ ', word))

Current Output, assuming word = ‘coffee’ and answer = ‘e’:

known_word = ' _  _  _  _  _  _ '

Expected Output, assuming word = ‘coffee’ and answer = ‘e’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

known_word = ' _  _  _  _ ee'

>Solution :

The setup as described in the question produces this output, which is what you say you expect

import re
word = 'coffee'
answer = 'e'
known_word = (re.sub('[^{}]'.format(answer), ' _ ', word))
known_word

# Output:
# ' _  _  _  _ ee'

So, we need to look for the error elsewhere. Doublecheck your answer and word inputs?

To answer the broader question, you should use re.escape() when inserting arbitrary text into a pattern. But for the given string "e" it doesn’t make a difference.

re.sub('[^{}]'.format(re.escape(answer)), ' _ ', word)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading