我有一个字符串:
path = "{'ResponseMetadata': {'Flag': 'Processed', 'Message': 'File Ingested successfully', 'INGEST_PATH': ['inward/emr_batch/manual_cars/xy99', ""manual_cars/xy99/2020/08/12/145938/ABC KPI's Jan 2018.csv""]}}
我只想替换字符串开头和结尾处的,而不是字符串中间的
我正在尝试使用python的replace函数来执行此任务
path = path.replace("\'", "\"")
但上述方法正在替换“字符串中的每一个位置和获得的输出”
{"ResponseMetadata": {"Flag": "Processed", "Message": "File Ingested successfully", "INGEST_PATH": ["inward/emr_batch/manual_cars/xy99", ""manual_cars/xy99/2020/08/12/145938/ABC KPI"s Jan 2018.csv""]}}
但我不希望KPI对KPI进行更改,我可以实现这一点的一种方法是再次使用替换功能,如下图所示,以获得所需的输出,,但下面方法的问题是,我需要在每个新场景中不断添加替换,我希望有一个通用的解决方案可以在这里得到一些帮助
path = path.replace("\'", "\"").replace('"s', "'s")
问候 马希
这里是一个简单的尝试,您可以简单地替换全部,然后替换回双引号,后跟字母s,如下所示
输出
您可以将目标锁定在任何要替换的位置,如
我推荐正则表达式
https://en.m.wikibooks.org/wiki/Python_Programming/Regular_Expression
https://docs.python.org/3/library/re.html
第二个链接显示正则表达式语言
sub具有以下签名:re.sub(模式、repl、字符串、计数=0、标志=0)
结果:{“ResponseMetadata”:{“Flag”:“Processed”,“Message”:“File inspected successfully”,“inspect_PATH”:[“introw/emr_batch/manual_cars/xy99”,“manual_cars/xy99/2020/08/12/145938/ABC KPI's Jan 2018.csv”]}
致意
首先,您的字符串无效。所以我用三个引号来定义它:
path = """{'ResponseMetadata': {'Flag': 'Processed', 'Message': 'File Ingested successfully', 'INGEST_PATH': ['inward/emr_batch/manual_cars/xy99', ""manual_cars/xy99/2020/08/12/145938/ABC KPI's Jan 2018.csv""]}}"""
迭代字符串的字符并检查周围字符的
isalpha()
如何:结果(同样,直接粘贴无效,除非它是三倍引号):
相关问题 更多 >
编程相关推荐