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>Put the legal characters in a set then use <a href="https://docs.python.org/3/reference/expressions.html?highlight=membership#membership-test-operations" rel="nofollow"><code>in</code></a> to test each character of the string.  Construct the new string using the <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a> method and a <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow">conditional expression</a>.</p>

<pre><code>&gt;&gt;&gt; s = "test.,/?~abcdefgh"
&gt;&gt;&gt; legal = set('.,/?~abcdefg')
&gt;&gt;&gt; s = ''.join(char if char in legal else '?' for char in s)
&gt;&gt;&gt; s
'?e??.,/?~abcdefg?'
&gt;&gt;&gt; 
</code></pre>

python python-2.7