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

Python 如何仅删除引号之间该部分的空白,python,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=

我有下面的字符串。我只需要删除单引号之间部分的空格。零件的其余部分在生产线中应完好无损

+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))'

可以用一个正则表达式语句来实现这一点吗?还是需要多行?

作为替代,您可能需要考虑有限状态机。我总是忘记了库,但是自己创建它非常简单。大概是这样的:

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)

另请参见:

尝试使用lookback和lookahead断言来提取该部分。谢谢你,马丁。这是一个伟大的代码。在这里,我可以找到更多信息来学习并用python编写FSM