Home > Software design >  How to escape backticks in Python3
How to escape backticks in Python3

Time:09-14

I'm trying to escape backticks in Python. For an example, I have this string.

>>> s = "my ` string"
>>> s
'my ` string'

Doing re.sub("`", "\`", s) will return 'my \\` string'.

How do I escape the backtick such that it will yield my \` string?

I need this because I will supply that string as an argument for a shell command, running inside a Jupyter Notebook.

! ./script.sh "$s"

CodePudding user response:

Backticks do not need to be escaped in Python. Your issue here is the backslash. This should be an easy fix, just change the second argument "\`" to r"\`". This will turn it into a string literal, that way nothing will be auto-escaped.

CodePudding user response:

How about this:

s = "my ` string"
for c in s:
    if c == '`':
        print(r"\`", end='')
    else: print(c, end='')

Output: my \` string

CodePudding user response:

You can use urllib. password = urllib.parse.quote_plus(password)

  • Related