简体   繁体   English

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

[英]How to define a string in python with double and single quotes

I am using python to communicate with the OS. 我正在使用python与操作系统进行通信。

I need to create a string of the following form: 我需要创建一个以下形式的字符串:

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

Note that my string MUST have the double quotes in it, but I am not sure how to do that since the double quotes are used in python for defining a string. 请注意,我的字符串必须有双引号,但我不知道如何做到这一点,因为双引号在python中用于定义字符串。

Then I do something like: 然后我做了类似的事情:

os.system(string)

But the system would only read the string with the double and single quotes in it. 但是系统只会读取带有双引号和单引号的字符串。

I tried: 我试过了:

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

I also tried the triple quotes suggested here but i get an error: 我也试过这里建议的三重引号,但是我收到一个错误:

>>> 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中存储包含单引号(')和双引号(“)的字符串

When you use a triply quoted string you need to remember that the string ends when Python finds a closing set of three quotes - and it is not greedy about it. 当你使用一个三重引用的字符串时,你需要记住当Python找到一组三个引号的结束时字符串结束 - 而且它并不贪心。 So you can: 所以你可以:

Change to wrapping in triple single quotes: 改为三重引号包装:

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

Escape the ending quote: 逃避结束语:

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

or add space around your quotes and call strip on the resulting string: 或者在引号周围添加空格并在结果字符串上调用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)

你可以逃避两种报价:

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

All four flavors of quotes: 所有四种报价:

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

Output: 输出:

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

I think this is what you are expecting: string = "\\"done('1') && done('2')\\"" 我认为这是你所期待的:string =“\\”done('1')&& done('2')\\“”

Ignore if this does not answer your question. 如果这不能回答您的问题,请忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM