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