Replacing unknown characters in a string Python 2.7
<p>How can I define characters(in a LIST or a STRING), and have any other characters replaced with.. lets say a '?'</p>

<p>Example:</p>

<pre><code>strinput = "abcdefg#~"
legal = '.,/?~abcdefg' #legal characters
while i not in legal:
    #Turn i into '?'
print output
</code></pre>

<p>If this is a large file, read in chunks, and apply <code>re.sub(..)</code> as below. <code>^</code> within a class (square brackets) stands for negation (similar to saying "anything other than")</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; char = '.,/?~abcdefg'
&gt;&gt;&gt; re.sub(r'[^' + char +']', '?', "test.,/?~abcdefgh")
'?e??.,/?~abcdefg?'
</code></pre>

python python-2.7