hareesh
hareesh

Reputation: 9

How to remove white spaces only in that part between quotation marks

I have the following string. I have to remove white spaces only in the part that is between single quotations. Rest of the part should be intact in the line,

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

So the output should be

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

Is it possible to do this with a single Regex statement ? or needed multiple lines ?

Upvotes: 0

Views: 60

Answers (1)

Martin Thoma
Martin Thoma

Reputation: 136327

As an alternative, you might want to consider finite state machine. I always forget the library, but it's super simple to create it on your own. Something like this:

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)

See also: Is list join really faster than string concatenation in python?

Upvotes: 1

Related Questions