简体   繁体   English

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

[英]How to replace a character at beginning and end of a string in python

I have a string:我有一个字符串:

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

I would like to replace ' at the beginning and end of the strings only and not in middle of strings.我只想在字符串的开头和结尾替换 ' 而不是在字符串的中间。

I am trying to make use of replace function of python to perform this task我正在尝试使用替换 python 的 function 来执行此任务

path = path.replace("\'", "\"")

but above approach is replacing the ' every where in string and output obtained is但上面的方法是替换字符串中的“每一个地方”,得到的 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""]}}

but I do not want KPI's to get change to KPI"s, one way which i can achieve this is to make use of replace function again like below to gain desired output , but then problem with below approch is that I need to keep on adding replace with each new scenario and I would like to have generic solution can some one help here.但我不希望 KPI 更改为 KPI"s,我可以实现此目的的一种方法是使用如下所示再次替换 function 以获得所需的 output ,但是下面的问题是我需要继续添加替换为每个新场景,我希望有通用解决方案可以在这里提供帮助。

path = path.replace("\'", "\"").replace('"s', "'s")

Regards Mahi问候马希

First, your string is invalid.首先,您的字符串无效。 So i'm defining it with triple quotes:所以我用三引号来定义它:

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

How about iterating over the string's characters and checking the surrounding characters for isalpha() :如何迭代字符串的字符并检查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)

Result (again, this is invalid to paste directly, unless it is triple quoted):结果(同样,直接粘贴是无效的,除非是三引号):

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

Here is simple attempt you can simply replace all and thereafter replace back the double quotes followed by letter s like the following这是一个简单的尝试,您可以简单地替换所有内容,然后替换双引号后跟字母 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_))

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

you can target everywhere you want to replace like你可以定位到任何你想替换的地方,比如

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

I would recommend regular expressions.我会推荐正则表达式。

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

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

second link shows the regular expression language.第二个链接显示正则表达式语言。

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 has the following signature: re.sub(pattern, repl, string, count=0, flags=0) sub 具有以下签名: re.sub(pattern, repl, string, count=0, flags=0)

  1. "([^']*)" <== this is a group, because of () and accepts all signs except ' "([^']*)" <== 这是一个组,因为 () 并且接受除 ' 之外的所有符号
  2. '"\1"' <== this is the replacer and will replace all founds with "(group)" '"\1"' <== 这是替换器,将用 "(group)" 替换所有发现

result: {"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""]}}结果: {“ResponseMetadata”:{“Flag”:“已处理”,“消息”:“文件摄取成功”,“INGEST_PATH”:[“inward/emr_batch/manual_cars/xy99”,“”manual_cars/xy99/2020/08 /12/145938/ABC KPI 的 Jan 2018.csv""]}}

Best regards此致

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Python的字符串开头或结尾删除字符 - removing a character from beginning or end of a string in Python 如何将 json 开头和结尾的 [ ] 替换为 { } 为 python - How to replace [ ] at beginning and end of json to { } with python 如何在Python的字符串的开头和结尾添加反斜杠(\\) - How to add a backlash (\) at the beginning and the end of a string in Python 如何在 Python 中删除字符串开头或结尾的停用词? - How to remove stopwords at the beginning or the end of a string in Python? python regex匹配并替换字符串的开头和结尾,但保持中间 - python regex match and replace beginning and end of string but keep the middle 如何在Python中匹配字符串或字符的开头 - How to match beginning of string or character in Python 如果 Pandas 中字符串的开头和结尾处可用,如何有效地删除字符? - How to effeciently remove character if available at the beginning and end of a string in Pandas? 尝试使用python为字符串的开头和结尾插入一个字符$,但我刚刚开始使用它们 - Trying to insert a character $ for beginning and end of a string using python, but i got them just in the beginning 如何在python中将字符添加到行首和行尾 - How to add a character to the beginning of a line and end of a line in python 如何替换 Python 中的字符串字符? - How to replace string character in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM