Robbie Morrison
Robbie Morrison

Reputation: 21

Creating singly escaped single and double quotes where newlines are also present / python

I need to transform a string containing single and double quotes and newline characters for use in a system call. Consider the following input string:

"""one'two\nthree"four"""

This should be transformed to the following output string:

"$'one\'two\nthree\"four'"

So that it can be submitted as a message argument in a git commit command:

git commit --message=$'one\'two\nthree\"four'

The odd syntax with the leading $ and surrounding single quotes ' is a bash construct described in the bash manpage in the section on quoting (search for QUOTING). I have tried many python functions including str.replace, re.sub, json.dumps, repr, and str.encode('unicode-escape'). But none have yielded the required transformation. It seems that, in this case, python is too high-level for its own good. Suggestions on how to proceed will be very gratefully received.

The system call itself will be made using code like this (omitting the try block for clarity):

import subprocess
call = ["git", "commit", "--message", "'one\'two\nthree\"four'"]
cpi = subprocess.run(call)

I may also use a git library of some description, but I have not done my homework yet for that.

Note: the unnecessary $ character in the last item in the above call list has been removed.

Upvotes: 2

Views: 144

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160607

Your wanted command is erroneous at the moment, it is not a valid Python string since a right " is missing, it should be:

"$'one\'two\nthree\"four'"

This is easily constructed by a simple .format call:

>>> "$'{}'".format("""one'two\nthree"four""") == "$'one\'two\nthree\"four'"
True

Upvotes: 1

Related Questions