如何在python中替换字符串开头和结尾的字符

2024-09-29 22:18:48 发布

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

我有一个字符串:

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")

问候 马希


Tags: path方法字符串messagemanualcarsreplacefile
3条回答

这里是一个简单的尝试,您可以简单地替换全部,然后替换回双引号,后跟字母s,如下所示

import re

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""]}}
'''

path_ = re.sub('\'', '\"', path)
print(re.sub('\"s','\'s', 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""]}}

您可以将目标锁定在任何要替换的位置,如

print(re.sub('KPI\"','KPI\'', path_))

我推荐正则表达式

https://en.m.wikibooks.org/wiki/Python_Programming/Regular_Expression

https://docs.python.org/3/library/re.html

第二个链接显示正则表达式语言

import re
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""]}}"""

m=re.sub(r"'([^']*)'",r'"\1"',path)

print(m)

sub具有以下签名:re.sub(模式、repl、字符串、计数=0、标志=0)

  1. “([^']*)”<;==这是一个组,因为()并接受除'
  2. “\1”<;==这是替换者,将用“(组)”替换所有Found

结果:{“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()如何:

out = []
for ix, char in enumerate(path):
  # first make sure we have a surrounding character on each side
  if ix > 0 and ix < len(path):
    # now check for a quote and make sure that one of the surrounding characters are not letters
    if char == "'" and not (path[ix-1].isalpha() and path[ix+1].isalpha()):
      # if we find that case, replace the single quote
      char = '"'
  # add the character to the out list
  out.append(char)

# join all the characters back together
output = ''.join(out)

print(output)

结果(同样,直接粘贴无效,除非它是三倍引号):

{"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""]}}

相关问题 更多 >

    热门问题