python-3.x 查找并删除/替换较大字符串的一部分

wpx232ag  于 2023-10-21  发布在  Python
关注(0)|答案(3)|浏览(90)

在我的python/Django项目中,我试图编写一个自定义异常类,我想避免向最终用户显示一些东西。
在下面的错误消息中,如果您看到项目名称prj-eng-d-nc-prcd-1077出现。我想在消息进入UI之前删除它。
我想找一个替代品。例如:

prj_name = 'prj-eng'
if prj_name in msg:
  msg = msg.replace(prj_name, '')

print (msg)

但这里的问题是项目名称将是动态的。它可以是prj-eng-d-nc-raw-1637prj-eng-d-nc-oauth-2218
我还尝试使用rfind(),我们可以找到子字符串的开始并替换,但这没有帮助。
谁能帮我解决一下。

{
        "jobs": [],
        "error": "Unable to process the request",
        "msg": "400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n" 
}

投入将是:

msg = "400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"

输出应为:

msg =  "400 Bad int64 value: \n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"
i7uq4tfw

i7uq4tfw1#

你正在寻找Python的regular expressions
使用re.sub(pattern, replacement, string),我们可以将string中的pattern替换为replacement
下面的代码演示了它的用法,前提是prj-eng-d-nc部分保持不变。

import re

msg = "text before prj-eng-d-nc-raw-1637 text after"
pattern = r"prj-eng-d-nc-\w*-\d*"
# replacing the pattern with empty string if matched
msg = re.sub(pattern, "", msg)
rmbxnbpk

rmbxnbpk2#

一个没有正则表达式魔术的解决方案的例子:

msg = "400 Bad int64 value: prj-eng-d-nc-prcd-1077\n\nLocation: us-central1\nJob ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n"

start = "400 Bad int64 value:"
end = "\n\nLocation:"

# find the index
front = msg.find(start)+len(start)
back = msg.find(end)

# slice via index
new_msg = msg[:front] + msg[back+1:]
print(new_msg)

输出量:

400 Bad int64 value:
Location: us-central1
Job ID: f8fc4fde-280b-4f35-ae9e-5fb92d2d0873

也可以使用print(repr(new_msg))打印一行。

piwo6bdm

piwo6bdm3#

若要从自定义异常类中的字符串中移除动态子字符串,可以使用正则表达式匹配该子字符串并将其替换为空字符串。

import re

class CustomException(Exception):
    def __init__(self, msg):
        # Remove project name from error message
        project_name_pattern = r'prj-eng(-\w+)*-\d+'
        self.msg = re.sub(project_name_pattern, '', msg)

Example try:raise CustomException('400 Bad int64 value:prj-eng-d-nc-prcd-1077\n\n位置:us-central 1\n作业ID:f8fc4fde-280b-4f35-ae9e-5fb92d2d0873\n')except CustomException as e:print(e.msg)

相关问题