簡體   English   中英

如何使用雙引號和單引號在python中定義字符串

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

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

如何在python中存儲包含單引號(')和雙引號(“)的字符串

當你使用一個三重引用的字符串時,你需要記住當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)

你可以逃避兩種報價:

s = '"done(\'1\') && done(\'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')"

我認為這是你所期待的:string =“\\”done('1')&& done('2')\\“”

如果這不能回答您的問題,請忽略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM