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

4 投票
4 回答
5979 浏览
提问于 2025-04-17 20:09

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

4 个回答

2

四种不同类型的引号:

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')"
3

你可以对这两种引号进行转义:

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

当你使用三重引号字符串时,需要记住,当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)

撰写回答