【问题标题】:How to define a string in python with double and single quotes如何在python中用双引号和单引号定义字符串
【发布时间】:2013-03-24 18:09:54
【问题描述】:

我正在使用 python 与操作系统进行通信。

我需要创建一个如下形式的字符串:

string = "done('1') && done('2')"

请注意,我的字符串中必须有双引号,但我不知道该怎么做,因为双引号在 python 中用于定义字符串。

然后我做类似的事情:

os.system(string)

但系统只会读取包含双引号和单引号的字符串。

我试过了:

>>> s = '"done('1') && done('2')"'
  File "<stdin>", line 1
    s = '"done('1') && done('2')"'
                ^
SyntaxError: invalid syntax

我也尝试了此处建议的三引号,但出现错误:

>>> s = """"done('1') && done('2')""""
  File "<stdin>", line 1
    s = """"done('1') && done('2')""""
                                     ^
SyntaxError: EOL while scanning string literal

How to store a string containing both single quote( ' ) and double quote( " ) in python

【问题讨论】:

标签: python


【解决方案1】:

当您使用triply quoted string 时,您需要记住字符串结束 当Python 找到一个由三个引号组成的闭合集合时——它并不贪心。所以你可以:

改为用三重引号括起来:

my_command = '''"done('1') && done('2')"'''

转义结束引号:

my_command = """"done('1') && done('2')\""""

或在引号周围添加空格并在结果字符串上调用strip

my_command = """
"done('1') && done('2')"
""".strip()
# Blank lines are for illustrative purposes only
# You can do it all on one line as well (but then it looks like you have
# 4 quotes (which can be confusing)

【讨论】:

  • 这行得通,但我在 python 中看到它是这样的:>>> my_command '"done(\'1\') && done(\'2\')"' (它添加了 \ ,当我将它传递给 os.system 时可以吗??谢谢!!!!
  • @Dnaiel - 是的,它是 - Python 只是使用相同字符串的替代表示。
【解决方案2】:

你可以转义这两种引号:

s = '"done(\'1\') && done(\'2\')"'

【讨论】:

    【解决方案3】:

    所有四种风格的引号:

    print('''"done('1') && done('2')"''')  # No escaping required here.
    print(""""done('1') && done('2')\"""")
    print("\"done('1') && done('2')\"")
    print('"done(\'1\') && done(\'2\')"')
    

    输出:

    "done('1') && done('2')"
    "done('1') && done('2')"
    "done('1') && done('2')"
    "done('1') && done('2')"
    

    【讨论】:

      【解决方案4】:

      我认为这是您所期望的: string = "\"完成('1') && 完成('2')\""

      如果这不能回答您的问题,请忽略。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        • 2016-02-10
        • 2021-02-26
        相关资源
        最近更新 更多