Austin Smith Austin Smith - 1 year ago 113
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 '?'


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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download