Python:如何移除(替换为“”)Python字符串中的撇号和逗号组合

wrrgggsh  于 2022-12-27  发布在  Python
关注(0)|答案(3)|浏览(126)

我有一个像这样的字符串,前面附加了一些奇怪的字符(整个字符串):

# Edited to make more clear. It is essentially this:

x = """
INFO     2022-12-27 16:56:25.843 request id: app - xxxxxx
', "INFO     2022-12-27 16:56:26.407 request id: app - xxxxxxx
", 'INFO     2022-12-27 16:56:26.407 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.497 request id: app - xxxxxxxx
"""

# So need to remove the comma and apostrophes in the 2nd and 3rd line of string object x

我想删除第2行和第3行中的', "', ",但由于撇号组合导致string literal is unterminated错误,因此很难替换或正则化它。

sdnqo3pr

sdnqo3pr1#

假设每一行日志总是以INFODEBUG这样的关键字开头,我们可以在多行模式下对文本进行正则表达式替换:

logs = """INFO     2022-12-27 16:56:25.843 request id: app - xxxxxx
', \"INFO     2022-12-27 16:56:26.407 request id: app - xxxxxxx
\", 'INFO     2022-12-27 16:56:26.407 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.497 request id: app - xxxxxxxx"""

output = re.sub(r'^[^A-Z]+', '', logs, flags=re.M)
print(output)

这将打印:

INFO     2022-12-27 16:56:25.843 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.407 request id: app - xxxxxxx
INFO     2022-12-27 16:56:26.407 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.497 request id: app - xxxxxxxx
j2datikz

j2datikz2#

string_test = f"""INFO     2022-12-27 16:56:25.843 request id: app - xxxxxx
', "INFO     2022-12-27 16:56:26.407 request id: app - xxxxxxx
", 'INFO     2022-12-27 16:56:26.407 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.497 request id: app - xxxxxxxx"""

string_test = string_test.replace(f"'", "")
print(string_test)

工作原理:将every '替换为nothing,将其删除。
希望这能帮上忙。

pu3pd22g

pu3pd22g3#

假设您真正想要做的是删除任何行中"INFO"之前的任何内容,则:

mystring = """INFO     2022-12-27 16:56:25.843 request id: app - xxxxxx
', "INFO     2022-12-27 16:56:26.407 request id: app - xxxxxxx
", 'INFO     2022-12-27 16:56:26.407 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.497 request id: app - xxxxxxxx"""

newstring = []

for line in mystring.splitlines():
    if (i := line.find('INFO')) >= 0:
        line = line[i:]
    newstring.append(line)

print('\n'.join(newstring))
    • 输出:**
INFO     2022-12-27 16:56:25.843 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.407 request id: app - xxxxxxx
INFO     2022-12-27 16:56:26.407 request id: app - xxxxxx
INFO     2022-12-27 16:56:26.497 request id: app - xxxxxxxx

相关问题