如何使用 .replace()
或任何类似的方法从长文本中删除不需要的字符。我希望从文本中删除的符号是 ',',{,},[,]
(不包括逗号)。我现有的文字是:
{'SearchText':'319 lizzie','ResultList':[{'PropertyQuickRefID':'R016698','PropertyType':'Real'}],'TaxYear':2018}
我尝试了以下代码:
content='''
{'SearchText':'319 lizzie','ResultList':[{'PropertyQuickRefID':'R016698','PropertyType':'Real'}],'TaxYear':2018}
'''
print(content.replace("'",""))
我得到的输出:[顺便说一句,如果我继续像 .replace().replace() 这样使用不同的符号,那么它就可以工作,但如果可能的话,我希望在单个实例中做同样的事情]
{SearchText:319 lizzie,ResultList:[{PropertyQuickRefID:R016698,PropertyType:Real}],TaxYear:2018}
我希望我可以使用像 .replace("',{,},[,]","") 这样的替换函数
。但是,我不寻求从 regex
派生的任何解决方案。字符串操作是我所期望的。提前致谢。
最佳答案
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
在 2.7 中我得到一个错误:
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
可以通过添加 # This Python file uses the following encoding: utf-8
作为源代码中的第一行来修复 - 然后给出相同的输出。
关于python - 无法从长字符串中剔除不需要的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47953966/