【问题标题】:How to print single '\' (slash) in python? [duplicate]如何在python中打印单个'\'(斜杠)? [复制]
【发布时间】:2017-03-16 14:10:42
【问题描述】:

我需要的输出是:

 'grep "key\":\"value" test_File.txt'

例如,我尝试的是..

>>> cmd = 'grep "key\":\"value" test_File.txt'
>>> cmd
 'grep "key":"value" test_File.txt'

但当我尝试转义实际斜杠时,它会打印两个斜杠。

>>> cmd = 'grep "key\\":\\"value" test_File.txt'
>>> cmd
 'grep "key\\":\\"value" test_File.txt'
 >>> 

我需要的是,我怎样才能得到第一行作为输出?

【问题讨论】:

  • 只是print(cmd)。您正在打印字符串的repr
  • 你到底想在这里完成什么?这看起来很像您试图打印要由 shell 执行的命令,并且对 shell 的引用规则感到非常困惑。一个有效的grep 命令看起来像grep '"key":"value"' test_File.txt,但我在这里猜测几个细节。使用subprocess,您希望避免使用shell=True,只传递['grep', '"key":"value"', 'test_File.txt'] 而不是字符串。
  • 是的,我正在尝试将此作为命令传递给子进程以执行,

标签: python python-2.7


【解决方案1】:

不要将 escaped 字符串与实际 打印的内容混淆

>>> cmd = '\'grep "key\\":\\"value\" test_File.txt\''
>>> print cmd
'grep "key\":\"value" test_File.txt'

我相信这符合您所需的输出。

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多