How can I escape any of the special shell characters in a Python string?
The following characters need to be escaped:
$,!,#,&,",',(,),|,<,>,`,\,;
For example say I have this string:
str="The$!cat#&ran\"'up()a|<>tree`\;"
TIA
Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.
Escape characters. Escape characters are used to remove the special meaning from a single character. A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.
Escape slashes and double-quotes. Surround entire command with double quotes so the command argument cannot be maliciously broken and commandeered with spaces.
\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .
In Python3, the required batteries are included as shlex.quote
.
shlex.quote(s)
Return a shell-escaped version of the string
s
. The returned value is a string that can safely be used as one token in a shell command line […].
In your example:
import shlex
s = "The$!cat#&ran\"'up()a|<>tree`\;"
print(shlex.quote(s))
Output:
'The$!cat#&ran"'"'"'up()a|<>tree`\;'
re.sub
will do the job:
re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1", astr)
Output
The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\\;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With