Python中單引號和雙引號的區別是什麼?
Python使用引號來表示字串物件。它們可以是單引號或雙引號。兩種方式都是正確的,並且工作方式相同;但是,當這些引號一起使用時,就會出現差異。
在本文中,我們將學習單引號和雙引號的區別。
Python中的單引號
單引號應該用於在Python中包裝小而短的字串,例如字串文字或識別符號。您必須記住,在用單引號表示字串時,使用單引號作為字串的一個字元將引發錯誤。在這種情況下,建議使用雙引號。讓我們透過一個例子來理解它。
示例
在下面的示例中,我們將表示多種型別的字串:單個單詞、多個單詞和多個句子。
name = 'Rahul' print(name) channel = 'Better Data Science' print(channel) paragraph = 'Rahul enjoys the content on Better Data Science. Rahul is awesome. Think like Rahul.' print(paragraph) hybrid = 'Hello "World"!' print(hybrid)
輸出
如果我們執行上面的程式,則輸出如下所示:
Rahul Better Data Science Rahul enjoys the content on Better Data Science. Rahul is awesome. Think like Rahul. Hello "World"!
示例
讓我們看看下面的另一個程式;在一個字串中使用多個單引號。
hybrid = 'Rahul's World' print(hybrid)
輸出
該程式引發瞭如下所示的語法錯誤:
File "/home/cg/root/96099/main.py", line 1 hybrid = 'Rahul's World' ^ SyntaxError: unterminated string literal (detected at line 1)
Python假設字串在“Rahul”之後結束,因此之後的內容都是語法錯誤。在程式碼編輯器中,此類錯誤很容易識別,因為“We”之後的部分顏色不同。
解決這個問題的方法是
停止使用縮寫(we are -> we're)——它們很不方便。
跳脫字元串——這是我們接下來要研究的一個選項。
使用雙引號。
跳脫字元串
跳脫字元串的基本目標是防止在計算機語言中使用特定字元。例如,我們不希望撇號被視為引號。
示例
要在Python中跳脫字元串字元,請使用反斜槓(\)符號
hybrid = 'Rahul's World' print(hybrid)
輸出
上面程式的輸出如下所示:
Rahul's World
示例
然而,反斜槓經常用作字串中的文字字元,例如表示計算機的路徑。讓我們看看如果你嘗試列印帶有跳脫字元的路徑會發生什麼。
print('C:\Users\John')
輸出
如果我們編譯並執行上面的程式,則會引發語法錯誤:
C:\Users\John C:\Users\John
可能不是你希望看到的。事實證明,有兩種方法可以避免跳脫字元:
如果你使用的是原始字串,請在第一個引號前寫'r'。
使用雙反斜槓來有效地轉義跳脫字元。
以下是執行這兩種方法的方法:
示例
#Write r before the first quote mark if you're using a raw string print(r'C:\Users\John') #Use a double backslash to effectively escape the escape character print('C:\Users\John')
輸出
如果我們執行上面的程式,則輸出如下所示:
C:\Users\John C:\Users\John
這兩個規則適用於單引號和雙引號括起來的字串。現在讓我們在本章的後面進一步討論在字串中使用雙引號。
Python中的雙引號
對於自然語言通訊、字串插值或當你知道字串中將包含單引號時,建議使用雙引號。讓我們使用下面的例子更好地理解。
示例
讓我們看看在下面的示例中,可以使用雙引號在Python中表示字串的各種情況。
name = 'Rahul' # Natural language print("It is easy for us to get confused with the single and double quotes in Python.") # String interpolation print(f"{name} said he is free today.") # No need to escape a character print("We're going out today.") # Quotation inside a string print("my favourite subject is 'maths'")
輸出
如果我們編譯並執行上面的程式,則會產生如下輸出:
It is easy for us to get confused with the single and double quotes in Python. Rahul said he is free today. We're going out today. my favourite subject is 'maths'
正如你所看到的,將引號嵌入到用雙引號括起來的字串中是很簡單的。我們也不需要像使用單引號那樣跳脫字元。
示例
記住,你不能再次在用雙引號括起來的字串中使用雙引號。這將導致與單引號相同的語法問題。讓我們在下面的示例中看看。
string = "He said, "I can't handle this anymore"." print(string)
輸出
上面程式的輸出如下所示:
File "/home/cg/root/22693/main.py", line 1 string = "He said, "I can't handle this anymore"." ^ SyntaxError: unterminated string literal (detected at line 1)
示例
為了避免這種情況,你可以應用上一節的方法,但你可以用單引號括起字串:
string = 'He said, "I cannot handle this anymore".' print(string)
輸出
輸出如下所示:
He said, "I cannot handle this anymore".
結論
在Python中,單引號和雙引號字串之間的區別微不足道。只要遵循你的程式設計約定,你可以將任何一個用於任何目的。在某些情況下,一種型別比另一種型別更有優勢。