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’
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)