如何删除引号之间的空白部分

2024-09-23 00:17:50 发布

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

我有下面的字符串。我只需要删除单引号之间部分的空格。剩下的部分应该是完整的

+amk=0 nog = 0 nf=1 par=1 mg =0.34e-6 sd='((nf != 1) ? (nf-1)) :0)' sca=0 scb=0 scc=0  pj='2* ((w+7.61e-6) + (l+8.32e-6 ))'

所以输出应该是

+amk=0 nog = 0 nf=1 par=1 mg =0.34e-6 sd='((nf!=1)?(nf-1)):0)' sca=0 scb=0 scc=0  pj='2*((w+7.61e-6)+(l+8.32e-6))'

是否可以用一个Regex语句来实现这一点?或者需要多条线路?你知道吗


Tags: 字符串语句sdregex空格sccparsca
1条回答
网友
1楼 · 发布于 2024-09-23 00:17:50

作为一种选择,您可能需要考虑有限状态机。我总是忘了图书馆,但它是超级简单的创建自己。像这样:

def remove_quoted_whitespace(input_str):
    """
    Remove space if it is quoted.

    Examples
        
    >>> remove_quoted_whitespace("mg =0.34e-6 sd='((nf != 1) ? (nf-1)) :0)'")
    "mg =0.34e-6 sd='((nf!=1)?(nf-1)):0)'"
    """
    output = []
    is_quoted = False
    quotechars = ["'"]
    ignore_chars = [' ']
    for c in input_str:
        if (c in ignore_chars and not is_quoted) or c not in ignore_chars:
            output.append(c)
        if c in quotechars:
            is_quoted = not is_quoted
    return ''.join(output)

另见:Is list join really faster than string concatenation in python?

相关问题 更多 >