Austin Smith Austin Smith - 2 months ago 7
Python Question

Replacing unknown characters in a string Python 2.7

How can I define characters(in a LIST or a STRING), and have any other characters replaced with.. lets say a '?'

Example:

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

Answer

Put the legal characters in a set then use in to test each character of the string. Construct the new string using the str.join() method and a conditional expression.

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