如何在Python字符串中转义任何特殊的shell字符?

需要转义以下字符:

$,!,#,&,",',(,),|,<,>,`,\,;

例如说我有这个字符串:
str="The$!cat#&ran\"'up()a|<>tree`\;"

TIA

最佳答案

在 Python3 中,所需的电池包含在 shlex.quote 中。



在你的例子中:

import shlex

s = "The$!cat#&ran\"'up()a|<>tree`\;"
print(shlex.quote(s))

输出:

'The$!cat#&ran"'"'"'up()a|<>tree`\;'

关于python - 如何在Python字符串中转义任何特殊的shell字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28120904/

10-13 07:20
查看更多