python - 无法从长字符串中剔除不需要的字符

标签 python string python-3.x replace

如何使用 .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/

相关文章:

linux - 在命令行上将字符串转换为十六进制

python - 如何使用发布数据重定向(Django)

python - 对 FITS 图像过采样后从 ra、dec 获取像素坐标

Python 列表索引超出范围

python - 有没有办法在其以前的版本中使用 Python 3.9 类型提示?

java - 如何比较列表和字符串数组(Java)?

string - 如何在clojure中以固定数量的字符分割字符串?

python - 在 Pandas 中转换数据框

python - 比较数据帧python匹配的行

python - 在 Python 中检索值的字典的嵌套字典列表