我该如何在Python字符串中转义任意特殊的shell字符?
以下字符需要被转义:
$,!,#,&,",',(,),|,<,>,`,\,;
例如,假设我有这个字符串:
str="The$!cat#&ran\"'up()a|<>tree`\;"
TIA
在Python3中,所需的工具已经被包含在shlex.quote
中。
shlex.quote(s)
返回字符串s
的shell转义版本。返回值是一个字符串,可以安全地用作shell命令行中的一个标记。[...]
import shlex
s = "The$!cat#&ran\"'up()a|<>tree`\;"
print(shlex.quote(s))
输出:
'The$!cat#&ran"'"'"'up()a|<>tree`\;'
shlex.quote
仅适用于 Python3。 - Padraic Cunninghamre.sub
可以完成这项工作:
re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1", astr)
输出
The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\\;
不确定为什么您想要转义所有内容而不是尽可能多地引用,但是这样做可以解决问题(如果需要,请将'@'
替换为字符串中不存在的另一个字符):
>>> escape_these = r'([$!#&"()|<>`\;' + "'])"
>>> print(re.sub(escape_these, r'@\1', s).replace('@','\\'))
The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\;
这可能需要稍微减少转义技巧,但不幸的是,字符串、re
和shell都使用\
(反斜杠)进行转义和其他特殊用途,这确实使事情有些复杂 :-).
str
。这会遮蔽内置的str
类。 - 5gon12eder