python - 如何在python中用双引号和单引号定义一个字符串

标签 python

我正在使用 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

最佳答案

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

更改为用三重引号引起来:

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 - 如何在python中用双引号和单引号定义一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15602118/

相关文章:

python - 在 imshow::matplotlib 中记录 x 尺度

python - 我从 Python 中的地理编码器中提取的一些坐标没有保存在我创建的变量中

python - 在没有追溯过滤的情况下创建对每个元素都有限制的组合

python - 合并多个txt文件(Python 3,UnicodeDecodeError)

python - 如何让正则表达式在 B 的最大匹配次数后停止搜索 A

python - 如何从选定列表中选择一个项目?

python - 使用 pybind11 通过预先存在的嵌入式 python 解释器公开 C++ 功能

python - 如何在 setuptools 中配置 svn 依赖链接

python - 使 django webapp 自行重启的最佳实践

python - 为什么子进程默认使用列表而不是带空格的字符串?