Reputation: 399
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
Upvotes: 12
Views: 12159
Reputation: 9417
re.sub
will do the job:
re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1", astr)
Output
The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\\;
Upvotes: 3
Reputation: 881605
Not sure why you want to escape everything rather than quote as much as feasible, but, this should do it (replace '@'
with another character not present in your string, if needed):
>>> escape_these = r'([$!#&"()|<>`\;' + "'])"
>>> print(re.sub(escape_these, r'@\1', s).replace('@','\\'))
The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\;
It may be doable with a tad less escape-trickery, but the unfortunate fact that strings, re
, and the shell, all use the \
(backslash) for escaping and other special purposes, does complicate things a bit:-).
Upvotes: 2
Reputation: 25409
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`\;'
Upvotes: 27