编码/解码C字符串文字

问题描述 投票:1回答:1

我有一个文本文件,其行为类似于C字符串。例如:

something = "some text\nin two lines\tand tab";
somethingElse = "some text with \"quotes\"";

在引号之间获取内容不是问题。问题是,稍后我要处理此字符串,而斜杠转义会使这变得困难。

我想解码这些字符串,对其进行处理,然后将其编码回C字符串文字。

因此来自原始输入

some text\\with line wrap\nand \"quote\"

我需要:

some text\with line wrap
and "quote"

反之亦然。

我尝试过的事情

我发现some API用于处理Python string literalsstring_escape),它接近我的需要,但是由于我正在处理C字符串,所以它是没有用的。我试图找到其他编解码器来匹配我的问题,但到目前为止还没有运气。

python replace escaping cstring
1个回答
0
投票

我也在寻找一个简单的解决方案,json模块似乎是最简单的解决方案。以下是我的快速技巧。请注意,如果/当both单引号(')和双引号(“)出现在同一字符串中时,仍然存在问题... 我怀疑您会遇到Unicode字符问题...

def c_decode(in_str:str) -> str:
    return json.loads(in_str.join('""' if '"' not in in_str else "''"))

def c_encode(in_str:str) -> str:
    """ Encode a string literal as per C"""
    return json.dumps(in_str)[1:-1]

还请注意,如果in_str"AB\n\r\tYZ" ...

then we alternatively have: ("%r"%(in_str.join('""')))[2:-2]
giving: 'AB\\n\\r\\tYZ' # almost the same c_encode above. 

希望这里[[某人有更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.