How to escape single quotes within single quoted strings

前端 未结 23 2185
说谎
说谎 2020-11-21 06:20

Let\'s say, you have a Bash alias like:

alias rxvt=\'urxvt\'

which works fine.

However:



        
23条回答
  •  醉酒成梦
    2020-11-21 06:45

    If you're generating the shell string within Python 2 or Python 3, the following may help to quote the arguments:

    #!/usr/bin/env python
    
    from __future__ import print_function
    
    try:  # py3
        from shlex import quote as shlex_quote
    except ImportError:  # py2
        from pipes import quote as shlex_quote
    
    s = """foo ain't "bad" so there!"""
    
    print(s)
    print(" ".join([shlex_quote(t) for t in s.split()]))
    

    This will output:

    foo ain't "bad" so there!
    foo 'ain'"'"'t' '"bad"' so 'there!'
    

提交回复
热议问题