无法从长字符串中删除不需要的字符

2024-04-26 01:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用.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("',{,},[,]","")这样的replace函数。然而,我并不想从regex中得到任何解决方案。字符串操作是我所期望的。提前谢谢。你知道吗


Tags: 方法文本符号content字符realreplace逗号
1条回答
网友
1楼 · 发布于 2024-04-26 01:35:26
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作为第一行来解决这个问题,这样就可以得到相同的输出。你知道吗

相关问题 更多 >