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

Dna*_*iel 3 python

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

我需要创建以下形式的字符串:

string = "done('1') && done('2')"
Run Code Online (Sandbox Code Playgroud)

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

然后我做这样的事情:

os.system(string)
Run Code Online (Sandbox Code Playgroud)

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

我试过:

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

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

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

如何在python中存储包含单引号(')和双引号(“)的字符串

Sea*_*ira 5

当您使用三引号字符串时,您需要记住,当 Python 找到一组三个引号的闭合集合时,字符串就结束了——它并不贪婪。这样你就可以:

改为用三重引号括起来:

my_command = '''"done('1') && done('2')"'''
Run Code Online (Sandbox Code Playgroud)

转义结束语:

my_command = """"done('1') && done('2')\""""
Run Code Online (Sandbox Code Playgroud)

或在引号周围添加空格并调用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)
Run Code Online (Sandbox Code Playgroud)