1

How can I remove unwanted characters from a long text using .replace() or any of that sort. Symbols I wish to kick out from the text are ',',{,},[,] (commas are not included). My existing text is:

{'SearchText':'319 lizzie','ResultList':[{'PropertyQuickRefID':'R016698','PropertyType':'Real'}],'TaxYear':2018}

I tried with the below code:

content='''
{'SearchText':'319 lizzie','ResultList':[{'PropertyQuickRefID':'R016698','PropertyType':'Real'}],'TaxYear':2018}
'''
print(content.replace("'",""))

Output I got: [btw, If i keep going like .replace().replace() with different symbols in it then it works but i wish to do the same in a single instance if its possible]

{SearchText:319 lizzie,ResultList:[{PropertyQuickRefID:R016698,PropertyType:Real}],TaxYear:2018}

I wish i could use replace function like .replace("',{,},[,]",""). However, I'm not after any solution derived from regex. String manipulation is what I expected. Thanks in advance.

SIM
  • 21,997
  • 5
  • 37
  • 109

1 Answers1

4
content=r"{'SearchText':'319 lizzie','ResultList':[{'PropertyQuickRefID':'R016698','PropertyType':'Real'}],'TaxYear':2018}"

igno = "{}[]''´´``''"
cleaned = ''.join([x for x in content if x not in igno])

print(cleaned)

PyFiddle 3.6:

SearchText:319 lizzie,ResultList:PropertyQuickRefID:R016698,PropertyType:Real,TaxYear:2018

In 2.7 I get an error:

Non-ASCII character '\xc2' in file main.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

wich can be fixed by adding # This Python file uses the following encoding: utf-8 as 1st line in source code - which then gives identical output.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Yes, it does the trick. Btw, ain't it possible to do the same using `.replace()` function with multiple characters in it? Gonna accept it in a while. – SIM Dec 23 '17 at 16:24
  • @topto you can also use string.transform - see https://stackoverflow.com/a/3939381/7505395 but with unicode it seems to be a pita - so i would stick to list comprehension: `for a man with a hammer, all problems tend to look like nails` ;) – Patrick Artner Dec 23 '17 at 16:50